Debian Codegraph @

tests/testlib/hypothesishelpers.py

raw
1 # Helper module to use the Hypothesis tool in tests
2 #
3 # Copyright 2015 David R. MacIver
4 #
5 # For details see http://hypothesis.readthedocs.org
6
7 import os
8 import sys
9 import traceback
10
11 try:
12 # hypothesis 2.x
13 from hypothesis.configuration import set_hypothesis_home_dir
14 from hypothesis import settings
15 except ImportError:
16 # hypothesis 1.x
17 from hypothesis.settings import set_hypothesis_home_dir
18 from hypothesis import Settings as settings
19 import hypothesis.strategies as st
20 from hypothesis import given
21
22 # hypothesis store data regarding generate example and code
23 set_hypothesis_home_dir(os.path.join(os.getenv('TESTTMP'), ".hypothesis"))
24
25
26 def check(*args, **kwargs):
27 """decorator to make a function a hypothesis test
28
29 Decorated function are run immediately (to be used doctest style)"""
30
31 def accept(f):
32 # Workaround for https://github.com/DRMacIver/hypothesis/issues/206
33 # Fixed in version 1.13 (released 2015 october 29th)
34 f.__module__ = '__anon__'
35 try:
36 with settings(max_examples=2000):
37 given(*args, **kwargs)(f)()
38 except Exception:
39 traceback.print_exc(file=sys.stdout)
40 sys.exit(1)
41
42 return accept
43
44
45 def roundtrips(data, decode, encode):
46 """helper to tests function that must do proper encode/decode roundtripping"""
47
48 @given(data)
49 def testroundtrips(value):
50 encoded = encode(value)
51 decoded = decode(encoded)
52 if decoded != value:
53 raise ValueError(
54 "Round trip failed: %s(%r) -> %s(%r) -> %r"
55 % (encode.__name__, value, decode.__name__, encoded, decoded)
56 )
57
58 try:
59 testroundtrips()
60 except Exception:
61 # heredoc swallow traceback, we work around it
62 traceback.print_exc(file=sys.stdout)
63 raise
64 print("Round trip OK")
65
66
67 # strategy for generating bytestring that might be an issue for Mercurial
68 bytestrings = (
69 st.builds(
70 lambda s, e: s.encode(e),
71 st.text(),
72 st.sampled_from(
73 [
74 'utf-8',
75 'utf-16',
76 ]
77 ),
78 )
79 ) | st.binary()