Debian Codegraph @

hypothesis-python/tests/cover/test_lookup_py314.py

raw
1 # This file is part of Hypothesis, which may be found at
2 # https://github.com/HypothesisWorks/hypothesis/
3 #
4 # Copyright the Hypothesis Authors.
5 # Individual contributors are listed in AUTHORS.rst and the git log.
6 #
7 # This Source Code Form is subject to the terms of the Mozilla Public License,
8 # v. 2.0. If a copy of the MPL was not distributed with this file, You can
9 # obtain one at https://mozilla.org/MPL/2.0/.
10
11 from collections.abc import Buffer
12 from dataclasses import dataclass
13
14 import pytest
15
16 from hypothesis import given, strategies as st
17
18 from tests.common.debug import find_any
19
20
21 @dataclass
22 class A:
23 constant = 42
24 x: int
25
26 # see https://docs.python.org/3/reference/datamodel.html#python-buffer-protocol
27 # and https://peps.python.org/pep-0688/
28 def __buffer__(self, flags):
29 return memoryview(
30 self.constant.to_bytes() + self.x.to_bytes(length=32, signed=True)
31 )
32
33
34 @given(st.from_type(memoryview[A]))
35 def test_resolve_bufferlike_memoryview(v):
36 assert isinstance(v, memoryview)
37 assert v[0] == A.constant
38 assert len(v) == 1 + 32
39
40
41 def test_errors_when___buffer___not_implemented():
42 class NoBuffer:
43 pass
44
45 @given(st.from_type(memoryview[NoBuffer]))
46 def f(v):
47 pass
48
49 with pytest.raises(
50 TypeError, match="a bytes-like object is required, not 'NoBuffer'"
51 ):
52 f()
53
54
55 def test_resolve_Buffer():
56 s = st.from_type(Buffer)
57 # on 3.12, we can generate neither. On 3.13, we can generate bytearray, because
58 # the removal of ByteString stops blocking bytearray from being the maximal
59 # registered type. On 3.14, we can generate both, because memoryview becomes
60 # generic.
61 find_any(s, lambda v: isinstance(v, memoryview))
62 find_any(s, lambda v: isinstance(v, bytearray))