File: test_optimiser.py

package info (click to toggle)
python-hypothesis 6.138.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 15,272 kB
  • sloc: python: 62,853; ruby: 1,107; sh: 253; makefile: 41; javascript: 6
file content (290 lines) | stat: -rw-r--r-- 8,714 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
# This file is part of Hypothesis, which may be found at
# https://github.com/HypothesisWorks/hypothesis/
#
# Copyright the Hypothesis Authors.
# Individual contributors are listed in AUTHORS.rst and the git log.
#
# This Source Code Form is subject to the terms of the Mozilla Public License,
# v. 2.0. If a copy of the MPL was not distributed with this file, You can
# obtain one at https://mozilla.org/MPL/2.0/.

import math

import pytest

from hypothesis import HealthCheck, assume, example, given, settings
from hypothesis.internal.conjecture.choice import ChoiceNode
from hypothesis.internal.conjecture.data import Status
from hypothesis.internal.conjecture.datatree import compute_max_children
from hypothesis.internal.conjecture.engine import ConjectureRunner, RunIsComplete
from hypothesis.internal.entropy import deterministic_PRNG
from hypothesis.internal.intervalsets import IntervalSet

from tests.conjecture.common import (
    buffer_size_limit,
    integer_constr,
    nodes,
)

runner_settings = settings(
    max_examples=100, database=None, suppress_health_check=list(HealthCheck)
)


def test_optimises_to_maximum():
    with deterministic_PRNG():

        def test(data):
            data.target_observations["m"] = data.draw_integer(0, 2**8 - 1)

        runner = ConjectureRunner(test, settings=runner_settings)
        runner.cached_test_function((0,))

        try:
            runner.optimise_targets()
        except RunIsComplete:
            pass

        assert runner.best_observed_targets["m"] == 255


def test_optimises_multiple_targets():
    with deterministic_PRNG():

        def test(data):
            n = data.draw_integer(0, 2**8 - 1)
            m = data.draw_integer(0, 2**8 - 1)
            if n + m > 256:
                data.mark_invalid()
            data.target_observations["m"] = m
            data.target_observations["n"] = n
            data.target_observations["m + n"] = m + n

        runner = ConjectureRunner(test, settings=runner_settings)
        runner.cached_test_function((200, 0))
        runner.cached_test_function((0, 200))

        try:
            runner.optimise_targets()
        except RunIsComplete:
            pass

        assert runner.best_observed_targets["m"] == 255
        assert runner.best_observed_targets["n"] == 255
        assert runner.best_observed_targets["m + n"] == 256


def test_optimises_when_last_element_is_empty():
    with deterministic_PRNG():

        def test(data):
            data.target_observations["n"] = data.draw_integer(0, 2**8 - 1)
            data.start_span(label=1)
            data.stop_span()

        runner = ConjectureRunner(test, settings=runner_settings)
        runner.cached_test_function((250,))

        try:
            runner.optimise_targets()
        except RunIsComplete:
            pass

        assert runner.best_observed_targets["n"] == 255


def test_can_optimise_last_with_following_empty():
    with deterministic_PRNG():

        def test(data):
            for _ in range(100):
                data.draw_integer(0, 3)
            data.target_observations[""] = data.draw_integer(0, 2**8 - 1)
            data.start_span(1)
            data.stop_span()

        runner = ConjectureRunner(
            test, settings=settings(runner_settings, max_examples=100)
        )
        runner.cached_test_function((0,) * 101)

        with pytest.raises(RunIsComplete):
            runner.optimise_targets()
        assert runner.best_observed_targets[""] == 255


@pytest.mark.parametrize("lower, upper", [(0, 1000), (13, 100), (1000, 2**16 - 1)])
@pytest.mark.parametrize("score_up", [False, True])
def test_can_find_endpoints_of_a_range(lower, upper, score_up):
    with deterministic_PRNG():

        def test(data):
            n = data.draw_integer(0, 2**16 - 1)
            if n < lower or n > upper:
                data.mark_invalid()
            if not score_up:
                n = -n
            data.target_observations["n"] = n

        runner = ConjectureRunner(
            test, settings=settings(runner_settings, max_examples=1000)
        )
        runner.cached_test_function(((lower + upper) // 2,))

        try:
            runner.optimise_targets()
        except RunIsComplete:
            pass
        if score_up:
            assert runner.best_observed_targets["n"] == upper
        else:
            assert runner.best_observed_targets["n"] == -lower


def test_targeting_can_drive_length_very_high():
    with deterministic_PRNG():

        def test(data):
            count = 0
            while data.draw_boolean(0.25):
                count += 1
            data.target_observations[""] = min(count, 100)

        runner = ConjectureRunner(test, settings=runner_settings)
        # extend here to ensure we get a valid (non-overrun) test case. The
        # outcome of the test case doesn't really matter as long as we have
        # something for the runner to optimize.
        runner.cached_test_function([], extend=50)

        try:
            runner.optimise_targets()
        except RunIsComplete:
            pass

        assert runner.best_observed_targets[""] == 100


def test_optimiser_when_test_grows_buffer_to_invalid():
    with deterministic_PRNG():

        def test(data):
            m = data.draw_integer(0, 2**8 - 1)
            data.target_observations["m"] = m
            if m > 100:
                data.draw_integer(0, 2**16 - 1)
                data.mark_invalid()

        runner = ConjectureRunner(test, settings=runner_settings)
        runner.cached_test_function((0,) * 10)

        try:
            runner.optimise_targets()
        except RunIsComplete:
            pass

        assert runner.best_observed_targets["m"] == 100


def test_can_patch_up_examples():
    with deterministic_PRNG():

        def test(data):
            data.start_span(42)
            m = data.draw_integer(0, 2**6 - 1)
            data.target_observations["m"] = m
            for _ in range(m):
                data.draw_boolean()
            data.stop_span()
            for i in range(4):
                if i != data.draw_integer(0, 2**8 - 1):
                    data.mark_invalid()

        runner = ConjectureRunner(
            test, settings=settings(runner_settings, max_examples=1000)
        )
        d = runner.cached_test_function((0, 0, 1, 2, 3, 4))
        assert d.status == Status.VALID

        try:
            runner.optimise_targets()
        except RunIsComplete:
            pass

        assert runner.best_observed_targets["m"] == 63


def test_optimiser_when_test_grows_buffer_to_overflow():
    with deterministic_PRNG():
        # NOTE: For compatibility with Python 3.9's LL(1)
        # parser, this is written as a nested with-statement,
        # instead of a compound one.
        with buffer_size_limit(2):

            def test(data):
                m = data.draw_integer(0, 2**8 - 1)
                data.target_observations["m"] = m
                if m > 100:
                    data.draw_integer(0, 2**64 - 1)
                    data.mark_invalid()

            runner = ConjectureRunner(test, settings=runner_settings)
            runner.cached_test_function((0,) * 10)

            try:
                runner.optimise_targets()
            except RunIsComplete:
                pass

            assert runner.best_observed_targets["m"] == 100


@given(nodes())
@example(
    ChoiceNode(
        type="bytes",
        value=b"\xb1",
        constraints={"min_size": 1, "max_size": 1},
        was_forced=False,
    )
)
@example(
    ChoiceNode(
        type="string",
        value="aaaa",
        constraints={
            "min_size": 0,
            "max_size": 10,
            "intervals": IntervalSet.from_string("abcd"),
        },
        was_forced=False,
    )
)
@example(
    ChoiceNode(
        type="integer", value=1, constraints=integer_constr(0, 200), was_forced=False
    )
)
def test_optimising_all_nodes(node):
    assume(compute_max_children(node.type, node.constraints) > 50)
    size_function = {
        "integer": lambda n: n,
        "float": lambda f: f if math.isfinite(f) else 0,
        "string": lambda s: len(s),
        "bytes": lambda b: len(b),
        "boolean": lambda b: int(b),
    }
    with deterministic_PRNG():

        def test(data):
            v = getattr(data, f"draw_{node.type}")(**node.constraints)
            data.target_observations["v"] = size_function[node.type](v)

        runner = ConjectureRunner(
            test, settings=settings(runner_settings, max_examples=50)
        )
        runner.cached_test_function([node.value])

        try:
            runner.optimise_targets()
        except RunIsComplete:
            pass