Questions tagged [python-hypothesis]
Hypothesis is a Python library for property-based testing; creating unit tests with pseudo-randomly generated data.
192
questions
0
votes
1
answer
25
views
Creating a pd.DataFrame with the Hypothesis library
I want to create some hypothesis based tests based on a random dataframe. I try to create a df using the following function:
@st.composite
def create_hypothesis_df(draw):
num_rows = draw(st....
3
votes
0
answers
38
views
Why is this Django test opening so many database connections?
I'm testing my Django REST API using Schemathesis and Django's built-in unittest. The code for my test suite is:
from contextlib import contextmanager
import schemathesis
from hypothesis import given,...
2
votes
1
answer
55
views
Using pytest and hypothesis, how can I make a test immediately return after discovering the first counterexample?
I'm developing a library, and I'm using hypothesis to test it.
I usually sketch out a (buggy) implementation of a function, implement tests, then iterate by fixing errors and running tests.
Usually ...
0
votes
1
answer
22
views
composite strategy doesn't work as planned
trying to create a rather complex strategy using python's Hypothesis doesn't work as planned.
the strategy is a fixed_dictionaries (recursive_strategy) where some of the dictioneries 'values' are ...
0
votes
0
answers
44
views
In pytest how can I avoid passing fixtures
I have a flask app and I'm trying to improve my pytest tests by using random data with hypothesis.
I have a fixture in conftest.py that yields a flask test client:
@pytest.fixture(scope="session&...
0
votes
1
answer
16
views
using st.deferred() to generate dictionary values using hypothesis with known keys, and specific value strategies doesn't work as expected
I'm trying to generate complex tree like dictionaries for testing my code.
the dictionaries are basically compound classes, that contains list of structs and more simpler fields.
I'm using hypothesis ...
1
vote
1
answer
25
views
Test one specific example in Hypothesis
Sometimes when I run pytest + hypothesis and one property-based test fails, I want to run that particular example with breakpoints etc.
@given(a=st.integers())
def test(a):
assert a != 4
...
0
votes
0
answers
41
views
How to use GUI reporting in python Hypothesis
As my hypothesis tests run, I want, for each test, to collect a few random examples that were used for that test, and demonstrate them via a gui. So for example if I have two tests def test_a(a: int) ...
0
votes
1
answer
50
views
Should probabilities be managed outside of Hypothesis?
from hypothesis import strategies as st
import random
import time
import math
Imagine your code expects a list sampling four elements. Some elements are more likely than others. You don't know the ...
0
votes
1
answer
49
views
selecting conditional code paths in hypothesis
Most conditional strategies seem to be data-driven. But what if I want to select a code path independently of any generated data?
For example, let's convert the grammar rule_a = rule_optional? rule_b ...
0
votes
1
answer
89
views
How to create and compare syrupy snapshots in hypothesis's stateful testing?
I want to create a hypothesis.stateful.RuleBasedStateMachine to run stateful testing in Python. When the test is running, I want it to be deterministic and either update some snapshots or compare with ...
2
votes
1
answer
43
views
With `hypothesis`, how to generate two values that satisfy an ordering relation?
When writing tests using hypothesis, from time to time I encounter a situation that I require two distinct values which satisfy a given relation. Think of the start and end of an interval, where start ...
0
votes
1
answer
57
views
How to use type hint properly for hypothesis's "stateful testing" example?
I'm trying to properly type hint hypothesis's stateful testing example:
import shutil
import tempfile
from collections import defaultdict
import hypothesis.strategies as st
from hypothesis.database ...
0
votes
1
answer
36
views
Getting .Flaky: Inconsistent data generation! in Python hypothesis
My test is to create a policy using (API), but API does not allow duplicate rule name.
so hypothesis when retries API is bound to give Duplicate name not allowed.
If add logic in my code to delete the ...
0
votes
1
answer
38
views
Strategy to generate a random datetime format
I'd like to define a Hypothesis strategy do generate a random datetime format.
Examples of what I'd like it to return:
'%Y-%m-%d'
'%d/%m/%Y %H:%M:%S'
'%m %d %Y %H:%M'
'%Y-%W-%a'
and so on.
Doesn't ...
0
votes
1
answer
140
views
VSCode creating a .hypothesis/unicode_data/13.0.0/charmap.json.gz file for every project
I'm not sure if it's happening because I installed a new library that has that issue, but now every time I run a new project VSCode creates a ".hypothesis/unicode_data/13.0.0/charmap.json.gz"...
2
votes
1
answer
142
views
Pytest: print something in conftest.py without requiring "-s"
I am using environment variables to control some Hypothesis settings in conftest.py:
test_max_examples = int(os.environ.get("TEST_MAX_EXAMPLES", "100").strip())
hypothesis.settings....
0
votes
1
answer
80
views
In the Hypothesis library for Python, why does the text() strategy cause custom strategies to retry?
I have a custom strategy built using composite that draws from text strategy internally.
Debugging another error (FailedHealthCheck.data_too_large) I realized that drawing from the text strategy can ...
1
vote
1
answer
114
views
In the Hypothesis testing library, what is the real difference between assume and filter?
Within the Hypothesis testing library for Python, there is the "assume" function, which "marks the example as bad, rather than failing the test". If there are too many "bad&...
2
votes
1
answer
461
views
How to combine the @fixture and the @given decorators in Python hypothesis testing?
I'm working with pytest and hypothesis for property-based testing in Python.
As a minimal example, suppose I want to test that my Matrix class constructor correctly assign the number of rows and ...
2
votes
1
answer
68
views
How to create a hypothesis strategy to sample uniformly over a range?
I am doing something roughly like this:
test_a.py
import unittest
import hypothesis
import hypothesis.extra.numpy
import numpy as np
from hypothesis import strategies as st
SHAPE = (10, )
...
0
votes
2
answers
337
views
How to make custom Hypothesis strategy to supply custom objects?
Suppose I have a class Thing
class Thing:
def __init__(self, x, y):
...
And suppose I have a function which acts on a list of things.
def do_stuff(list_of_things):
...
I would like ...
0
votes
1
answer
61
views
Create a pd.DataFrame with a minimum number of rows using hypothesis
I'm using the hypothesis library and I would like to create a pd.DataFrame with three columns. Each column may contain integer values, either +1, 0, or -1. The values doesn't need to be unique. Also, ...
1
vote
0
answers
48
views
Efficient way of requiring that a certain portion of elements from a Hypothesis strategy must be unique
What is the most efficient way of requiring rather than that all elements generated according to a hypothesis strategy are unique, at least a certain portion are unique?
Strategies such as the ...
0
votes
1
answer
51
views
Generating an interval set in hypothesis
I have some code that works with intervals, which are really just python dicts with the following structure:
{
"name": "some utf8 string",
"start": 0.0, # 0.0 &...
0
votes
1
answer
56
views
How to generate complex Hypothesis data frames with internal row and column dependencies?
Is there an elegant way of using hypothesis to directly generate complex pandas data frames with internal row and column dependencies? Let's say I want columns such as:
[longitude][latitude][some-text-...
0
votes
1
answer
47
views
How can I generate instances of a class with inter-dependent attributes?
Assume this simple case: (reposted and lightly edited from the Hypothesis mailing list)
@dataclass
class A:
names: list[str]
ages: dict[str, float]
How could I write a strategy which generates ...
0
votes
1
answer
73
views
Why use recursive() instead of deferred()?
I needed a strategy for arbitrary JSON values and after reading about the gotchas of using composite() for recursive data came up with this
json_primitives = st.one_of(
st.none(),
st.booleans()...
3
votes
1
answer
152
views
Hypothesis create column with pd.datetime dtype in given test-dataframe
I want to test whether a certain method can handle different dates in a pandas dataframe, which it takes as an argument. The following example should clarify what kind of setup I want. In the example ...
1
vote
1
answer
130
views
Can you create a function with a specific signature without using eval?
I’ve written some code that inspects function signatures, and I would like to generate test cases for it. For this, I need to be able to construct objects that result in a given Signature object when ...
1
vote
1
answer
138
views
Hypothesis, using "one_of" with Pandas dtypes in the "data_frames" strategy
I would like to construct a Pandas series that is any of several dtypes.
I was hoping to do something like this:
from hypothesis import given
import hypothesis.strategies as hs
import hypothesis.extra....
0
votes
1
answer
184
views
Hypothesis strategy from_regex does not respect min_size and max_size
I am having issues with Hypothesis generating strings which do not respect the given min/max sizes. Example:
@given(
st.text(
alphabet=st.from_regex(regex=r"^[a-z][b-z]$", ...
1
vote
1
answer
2k
views
Handling of pydantic ValidationError when testing with hypothesis.given
When using hypothesis to test my pydantic models, I do not know how to handle ValidationError thrown by custom validators. This is a very small example that shows the problem:
# model
from pydantic ...
0
votes
1
answer
292
views
Randomizing a user dataclass with pytest and hypothesis
I can manually define an Address builder strategy:
import attrs
from hypothesis import given
import hypothesis.strategies as st
@attrs.frozen(kw_only=True)
class Address:
street: str
city: ...
2
votes
1
answer
673
views
Create hypothesis strategy that returns unique values
I'm trying to create a hypothesis strategy which produces integers with no repeats. Here's my code:
import hypothesis
import hypothesis.strategies as strategies
def unique(strat):
previous = set(...
1
vote
1
answer
65
views
generate matrix with independent columns
I am trying to generate matrices with independent columns. At the moment I am using assume which works, but requires a lot of computation:
import sys
import hypothesis.strategies as st
import numpy as ...
0
votes
1
answer
97
views
Hypothesis python package for onehots and longitudinal data
For context I work with mixed tabular data. I have complex data pipelines that I’d like to make sure works on any configuration of data.
I see the pandas add-on/extra and have some questions related ...
0
votes
1
answer
140
views
taking square using "value**2" results causes an overflow while "value*value" is fine
Given the same input, x**2 gives an integer overflow while x*x works fine.
I am not sure if this is because of the python's internal implementation of those operator or if this is a bug in the ...
1
vote
1
answer
366
views
Pytest and Hypothesis: given in nested async functions
I have a problem with a test case as shown below. I want to test a function of class Foo, but I can't create any instance of class Foo until I create my test function. Then for creation test values ...
0
votes
1
answer
22
views
How to check internal size parameters that controls example generation
In PropEr, there's an internal variable called Size that represents the size of generated example.
For instance, when we have 2 variables and would like to make them proportional each other, PropEr ...
0
votes
1
answer
27
views
`event` throws TypeError caused by WeakKeyDictionary when tuple is passed
I wanted to see the statistics of list values and I passed the value to event() after converting it to tuple to make it hashable.
@dataclass(frozen=True)
class Foo:
x: int
y: str
def ...
6
votes
1
answer
2k
views
Use pytest fixtures in test with hypothesis
As the documentation and this article state, it should be possible to use hypothesis strategies and pytest fixtures in the same test.
But executing this example code of the article:
from hypothesis ...
0
votes
1
answer
35
views
Collecting sample statistics in the test
I am wondering if there's a way to report statistics of examples in the test using Hypothesis. In other PBTs framework, such as PropEr, provide a way (in this case collect/2) to generate a report of ...
0
votes
1
answer
297
views
Preventing "Interesting" results from python-hypothesis
I am doing some hypothesis testing on async test. My code create and alter databases real-time, and I'm facing a problem with cleanup.
Basically, most of the time, I can cleanup the database without a ...
2
votes
2
answers
197
views
Hypothesis library: strategy for the complement of some other strategy
I'm using the Hypothesis library for unit testing. With this library you don't hand-pick inputs, but you define the complete set of inputs for which you want to test. Hypothesis will then sample from ...
0
votes
2
answers
457
views
How to block the hypothesis pytest plugin
According to the pytest documentation, I can block a plugin using -p no:name. I confirmed that this works for other plugins. However, when I try this with hypothesis it has no effect:
(ska3-next) ➜ ...
-1
votes
1
answer
114
views
How to use @seed in hypothesis?
I'm trying to use @seed here: https://hypothesis.readthedocs.io/en/latest/reproducing.html#reproducing-a-test-run-with-seed
But when I include it before @given, I get the error
NameError: name 'seed' ...
0
votes
1
answer
147
views
Generating large examples with the Hypothesis testing package
I am trying to use Hypothesis to stress test some code. I need a large example, but Hypthesis has some built in mechanism to prevent that.
For example:
from hypothesis import strategies as st
st.lists(...
0
votes
1
answer
476
views
Python Hypothesis testing: Is there a way to avoid drawing a LazyStrategy?
If Python hypothesis strategies are too deeply nested, using draw will not create an actual example, but a LazyStrategy. This can be quite problematic at times because the resulting object behaves ...
0
votes
1
answer
148
views
Python Hypothesis mixing strategies behavior for DataFrames
The following works as expected
from datetime import datetime
from hypothesis.extra.pandas import columns, data_frames, indexes
import hypothesis.strategies as st
def boundarize(d: datetime):
...