File: test_reproduce_failure.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 (248 lines) | stat: -rw-r--r-- 7,155 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
# 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 base64
import re
import zlib

import pytest

from hypothesis import (
    Verbosity,
    __version__,
    example,
    given,
    reject,
    reproduce_failure,
    settings,
    strategies as st,
)
from hypothesis.core import decode_failure, encode_failure
from hypothesis.errors import DidNotReproduce, InvalidArgument, UnsatisfiedAssumption
from hypothesis.internal.conjecture.choice import choice_equal

from tests.common.utils import Why, capture_out, no_shrink, xfail_on_crosshair
from tests.conjecture.common import nodes, nodes_inline


@example(nodes_inline("0" * 100))  # shorter compressed than not
@given(st.lists(nodes()))
def test_encoding_loop(nodes):
    choices = [n.value for n in nodes]
    looped = decode_failure(encode_failure(choices))
    assert len(choices) == len(looped)
    for pre, post in zip(choices, looped):
        assert choice_equal(pre, post)


@example(base64.b64encode(b"\2\3\4"))
@example(b"\t")
@example(base64.b64encode(b"\1\0"))  # zlib error
@example(base64.b64encode(b"\1" + zlib.compress(b"\xff")))  # choices_from_bytes error
@given(st.binary())
def test_decoding_may_fail(t):
    try:
        decode_failure(t)
        reject()
    except UnsatisfiedAssumption:
        raise  # don't silence the reject()
    except InvalidArgument:
        pass
    except Exception as e:
        raise AssertionError("Expected an InvalidArgument exception") from e


def test_invalid_base_64_gives_invalid_argument():
    with pytest.raises(InvalidArgument) as exc_info:
        decode_failure(b"/")
    assert "Invalid base64 encoded" in exc_info.value.args[0]


def test_reproduces_the_failure():
    b = b"hello world"
    n = len(b)

    @reproduce_failure(__version__, encode_failure([b]))
    @given(st.binary(min_size=n, max_size=n))
    def test_outer(x):
        assert x != b

    @given(st.binary(min_size=n, max_size=n))
    @reproduce_failure(__version__, encode_failure([b]))
    def test_inner(x):
        assert x != b

    with pytest.raises(AssertionError):
        test_outer()
    with pytest.raises(AssertionError):
        test_inner()


def test_errors_if_provided_example_does_not_reproduce_failure():
    b = b"hello world"
    n = len(b)

    @reproduce_failure(__version__, encode_failure([b]))
    @given(st.binary(min_size=n, max_size=n))
    def test(x):
        assert x == b

    with pytest.raises(DidNotReproduce):
        test()


def test_errors_with_did_not_reproduce_if_the_shape_changes():
    b = b"hello world"
    n = len(b)

    @reproduce_failure(__version__, encode_failure([b]))
    @given(st.binary(min_size=n, max_size=n) | st.integers())
    def test(v):
        assert v == b

    with pytest.raises(DidNotReproduce):
        test()


def test_errors_with_did_not_reproduce_if_rejected():
    b = b"hello world"
    n = len(b)

    @reproduce_failure(__version__, encode_failure([b]))
    @given(st.binary(min_size=n, max_size=n))
    def test(x):
        reject()

    with pytest.raises(DidNotReproduce):
        test()


@xfail_on_crosshair(Why.symbolic_outside_context)
def test_prints_reproduction_if_requested():
    failing_example = None

    @settings(print_blob=True, database=None, max_examples=100)
    @given(st.integers())
    def test(i):
        nonlocal failing_example
        if failing_example is None and i != 0:
            failing_example = i
        assert i != failing_example

    with pytest.raises(AssertionError) as err:
        test()
    notes = "\n".join(err.value.__notes__)
    assert "@reproduce_failure" in notes

    exp = re.compile(r"reproduce_failure\(([^)]+)\)", re.MULTILINE)
    extract = exp.search(notes)
    reproduction = eval(extract.group(0))
    test = reproduction(test)

    with pytest.raises(AssertionError):
        test()


def test_does_not_print_reproduction_for_simple_examples_by_default():
    @settings(print_blob=False)
    @given(st.integers())
    def test(i):
        raise AssertionError

    with capture_out() as o:
        # 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 pytest.raises(AssertionError):
            test()
    assert "@reproduce_failure" not in o.getvalue()


def test_does_not_print_reproduction_for_simple_data_examples_by_default():
    @settings(print_blob=False)
    @given(st.data())
    def test(data):
        data.draw(st.integers())
        raise AssertionError

    with capture_out() as o:
        # 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 pytest.raises(AssertionError):
            test()
    assert "@reproduce_failure" not in o.getvalue()


def test_does_not_print_reproduction_for_large_data_examples_by_default():
    @settings(phases=no_shrink, print_blob=False)
    @given(st.data())
    def test(data):
        b = data.draw(st.binary(min_size=1000, max_size=1000))
        if len(zlib.compress(b)) > 1000:
            raise ValueError

    with capture_out() as o:
        # 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 pytest.raises(ValueError):
            test()
    assert "@reproduce_failure" not in o.getvalue()


class Foo:
    def __repr__(self):
        return "not a valid python expression"


def test_does_not_print_reproduction_if_told_not_to():
    @settings(print_blob=False)
    @given(st.integers().map(lambda x: Foo()))
    def test(i):
        raise ValueError

    with capture_out() as o:
        # 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 pytest.raises(ValueError):
            test()

    assert "@reproduce_failure" not in o.getvalue()


def test_raises_invalid_if_wrong_version():
    b = b"hello world"
    n = len(b)

    @reproduce_failure("1.0.0", encode_failure([b]))
    @given(st.binary(min_size=n, max_size=n))
    def test(x):
        pass

    with pytest.raises(InvalidArgument):
        test()


def test_does_not_print_reproduction_if_verbosity_set_to_quiet():
    @given(st.data())
    @settings(verbosity=Verbosity.quiet, print_blob=False)
    def test_always_fails(data):
        assert data.draw(st.just(False))

    with capture_out() as out:
        # 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 pytest.raises(AssertionError):
            test_always_fails()

    assert "@reproduce_failure" not in out.getvalue()