How to use the hypothesis.strategies.floats function in hypothesis

To help you get started, we’ve selected a few hypothesis examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github infobyte / faraday / tests / test_api_vulnerability.py View on Github external
def vulnerability_json(parent_id, parent_type, vuln=None):
    vuln_dict = {
        'metadata': st.fixed_dictionaries({
            'update_time': st.floats(),
            'update_user': st.one_of(st.none(), st.text()),
            'update_action': st.integers(),
            'creator': st.text(),
            'create_time': st.floats(),
            'update_controller_action': st.text(),
            'owner': st.one_of(st.none(), st.text())}),
        'obj_id': st.integers(),
        'owner': st.one_of(st.none(), st.text()),
        'parent': st.sampled_from([parent_id]),
        'parent_type': st.sampled_from([parent_type]),
        'type': st.one_of(
            st.sampled_from([
            "Vulnerability", "Invalid", None]),
            st.text()
        ),
        'ws': st.one_of(st.none(), st.text()),
        'confirmed': st.booleans(),
        'data': st.one_of(st.none(), st.text()),
        'desc': st.one_of(st.none(), st.text()),
        'easeofresolution': st.sampled_from(['trivial',
github mozillazg / pypy / extra_tests / test_json.py View on Github external
with pytest.raises(UnicodeDecodeError) as excinfo:
        json.dumps((u"\u1234", "\xc0"), ensure_ascii=False)
    assert str(excinfo.value).startswith(
        "'ascii' codec can't decode byte 0xc0 ")
    with pytest.raises(UnicodeDecodeError) as excinfo:
        json.dumps(("\xc0", u"\u1234"), ensure_ascii=False)
    assert str(excinfo.value).startswith(
        "'ascii' codec can't decode byte 0xc0 ")

def test_issue2191():
    assert is_(json.dumps(u"xxx", ensure_ascii=False), u'"xxx"')

jsondata = strategies.recursive(
    strategies.none() |
    strategies.booleans() |
    strategies.floats(allow_nan=False) |
    strategies.text(),
    lambda children: strategies.lists(children) |
        strategies.dictionaries(strategies.text(), children))

@given(jsondata)
def test_roundtrip(d):
    assert json.loads(json.dumps(d)) == d
github davidmascharka / MyNN / tests / test_losses.py View on Github external
def test_focal_loss(num_datum, num_classes, alpha, gamma, data, grad):


    scores = data.draw(hnp.arrays(shape=(num_datum, num_classes),
                                  dtype=float,
                                  elements=st.floats(1, 100)))

    assume((abs(scores.sum(axis=1)) > 0.001).all())

    scores_mygrad = Tensor(scores)
    scores_nn = Tensor(scores)

    truth = np.zeros((num_datum, num_classes))
    targets = data.draw(st.tuples(*(st.integers(0, num_classes - 1) for i in range(num_datum))))

    truth[range(num_datum), targets] = 1

    probs = softmax(scores_mygrad)
    mygrad_focal_loss = sum(truth * (-alpha * (1 - probs + 1e-14)**gamma * log(probs))) / num_datum
    mygrad_focal_loss.backward(grad)

    nn_loss = softmax_focal_loss(scores_nn, targets, alpha=alpha, gamma=gamma)
github rsokl / noggin / tests / test_LivePlot.py View on Github external
        | st.lists(st.floats(max_value=10)).filter(
            lambda x: len(x) != 2 or any(i <= 0 for i in x)
        )
    ),
)
def test_bad_figsize(plotter: LivePlot, bad_size):
    with pytest.raises(ValueError):
        plotter.figsize = bad_size
github SiLab-Bonn / pylandau / tests / test_fuzzing.py View on Github external
    @given(st.floats(constrains.LANDAU_MIN_MPV,
                     constrains.LANDAU_MAX_MPV,
                     allow_nan=False,
                     allow_infinity=False),
           st.floats(constrains.LANDAU_MIN_ETA,
                     constrains.LANDAU_MAX_ETA,
                     allow_nan=False,
                     allow_infinity=False),
           st.floats(constrains.LANDAU_MIN_A,
                     constrains.LANDAU_MAX_A,
                     allow_nan=False,
                     allow_infinity=False))
    def test_landau_stability(self, mpv, eta, A):
        ''' Check Landau outputs for same input parameters '''
        x = np.linspace(mpv - 5 * eta, mpv + 5 * eta, 1000)
        y_1 = pylandau.landau(x, mpv=mpv, eta=eta, A=A)
        y_2 = pylandau.landau(x, mpv=mpv, eta=eta, A=A)
github pikepdf / pikepdf / tests / test_object.py View on Github external
@given(floats())
def test_decimal_from_float(f):
    d = Decimal(f)
    if isfinite(f) and d.is_finite():
        try:
            # PDF is limited to ~5 sig figs
            decstr = str(d.quantize(Decimal('1.000000')))
        except InvalidOperation:
            return  # PDF doesn't support exponential notation
        try:
            py_d = Object.parse(decstr)
        except RuntimeError as e:
            if 'overflow' in str(e) or 'underflow' in str(e):
                py_d = Object.parse(str(f))

        assert isclose(py_d, d, abs_tol=1e-5), (d, f.hex())
    else:
github Tinche / cattrs / tests / test_structure.py View on Github external
from cattr import Converter
from cattr._compat import bytes, is_bare, is_union_type, unicode
from cattr.converters import NoneType

from . import (
    dicts_of_primitives,
    enums_of_primitives,
    lists_of_primitives,
    primitive_strategies,
    seqs_of_primitives,
)
from ._compat import change_type_param

ints_and_type = tuples(integers(), just(int))
floats_and_type = tuples(floats(allow_nan=False), just(float))
strs_and_type = tuples(text(), just(unicode))
bytes_and_type = tuples(binary(), just(bytes))

primitives_and_type = one_of(
    ints_and_type, floats_and_type, strs_and_type, bytes_and_type
)

mut_set_types = sampled_from([Set, MutableSet])
set_types = one_of(mut_set_types, just(FrozenSet))


def create_generic_type(generic_types, param_type):
    """Create a strategy for generating parameterized generic types."""
    return one_of(
        generic_types,
        generic_types.map(lambda t: t[Any]),
github pytorch / pytorch / test / hypothesis_utils.py View on Github external
def tensor(draw, shapes=None, elements=None, qparams=None):
    if isinstance(shapes, SearchStrategy):
        _shape = draw(shapes)
    else:
        _shape = draw(st.sampled_from(shapes))
    if qparams is None:
        if elements is None:
            elements = st.floats(-1e6, 1e6)
        X = draw(stnp.arrays(dtype=np.float32, elements=elements, shape=_shape))
        assume(not (np.isnan(X).any() or np.isinf(X).any()))
        return X, None
    qparams = draw(qparams)
    if elements is None:
        min_value, max_value = _get_valid_min_max(qparams)
        elements = st.floats(min_value, max_value)
    X = draw(stnp.arrays(dtype=np.float32, elements=elements, shape=_shape))
    return X, qparams
github HypothesisWorks / hypothesis / src / hypothesis / internal / strategymethod.py View on Github external
def define_strategy_for_float_Range(specifier, settings):
            return st.floats(specifier.start, specifier.end)