def rule_label(self, name):
     try:
         return self.__rule_labels[name]
     except KeyError:
         return self.__rule_labels.setdefault(
             name, calc_label_from_name("LARK:%s" % (name,))
         )
Example #2
0
 def rule_label(self, name):
     try:
         return self.__rule_labels[name]
     except KeyError:
         return self.__rule_labels.setdefault(
             name, calc_label_from_name("LARK:%s" % (name,))
         )
Example #3
0
#
# END HEADER

from __future__ import division, print_function, absolute_import

from enum import IntEnum

import attr

from hypothesis.errors import Frozen, StopTest, InvalidArgument
from hypothesis.internal.compat import hbytes, hrange, text_type, \
    bit_length, benchmark_time, int_from_bytes, unicode_safe_repr
from hypothesis.internal.escalation import mark_for_escalation
from hypothesis.internal.conjecture.utils import calc_label_from_name

TOP_LABEL = calc_label_from_name('top')
DRAW_BYTES_LABEL = calc_label_from_name('draw_bytes() in ConjectureData')


class Status(IntEnum):
    OVERRUN = 0
    INVALID = 1
    VALID = 2
    INTERESTING = 3

    def __repr__(self):
        return 'Status.%s' % (self.name,)


@attr.s(slots=True)
class Example(object):
        1.7976931348623157e308,
        3.402823466e38,
        9007199254740992,
        1 - 10e-6,
        2 + 10e-6,
        1.192092896e-07,
        2.2204460492503131e-016,
    ]
    + [float("inf"), float("nan")] * 5,
    key=flt.float_to_lex,
)
NASTY_FLOATS = list(map(float, NASTY_FLOATS))
NASTY_FLOATS.extend([-x for x in NASTY_FLOATS])

FLOAT_STRATEGY_DO_DRAW_LABEL = calc_label_from_name(
    "getting another float in FloatStrategy"
)


class FloatStrategy(SearchStrategy):
    """Generic superclass for strategies which produce floats."""

    def __init__(self, allow_infinity, allow_nan):
        SearchStrategy.__init__(self)
        assert isinstance(allow_infinity, bool)
        assert isinstance(allow_nan, bool)
        self.allow_infinity = allow_infinity
        self.allow_nan = allow_nan

        self.nasty_floats = [f for f in NASTY_FLOATS if self.permitted(f)]
        weights = [0.2 * len(self.nasty_floats)] + [0.8] * len(self.nasty_floats)
Example #5
0
from hypothesis._settings import Verbosity
from hypothesis._settings import settings as Settings
from hypothesis._settings import note_deprecation
from hypothesis.reporting import report, verbose_report, current_verbosity
from hypothesis.strategies import just, one_of, runner, tuples, \
    fixed_dictionaries
from hypothesis.vendor.pretty import CUnicodeIO, RepresentationPrinter
from hypothesis.internal.compat import int_to_bytes, string_types
from hypothesis.internal.reflection import proxies, nicerepr
from hypothesis.internal.conjecture.data import StopTest
from hypothesis.internal.conjecture.utils import integer_range, \
    calc_label_from_name
from hypothesis.searchstrategy.strategies import OneOfStrategy, \
    SearchStrategy

STATE_MACHINE_RUN_LABEL = calc_label_from_name('another state machine step')

if False:
    from typing import Any, Dict, List, Text  # noqa


class TestCaseProperty(object):  # pragma: no cover

    def __get__(self, obj, typ=None):
        if obj is not None:
            typ = type(obj)
        return typ._to_test_case()

    def __set__(self, obj, value):
        raise AttributeError(u'Cannot set TestCase')
Example #6
0
    3. If the unbiased exponent is in the range [1, 51] then we reverse the
       low k bits, where k is 52 - unbiased exponen.

The low bits correspond to the fractional part of the floating point number.
Reversing it bitwise means that we try to minimize the low bits, which kills
off the higher powers of 2 in the fraction first.
"""

MAX_EXPONENT = 0x7ff

SPECIAL_EXPONENTS = (0, MAX_EXPONENT)

BIAS = 1023
MAX_POSITIVE_EXPONENT = (MAX_EXPONENT - 1 - BIAS)

DRAW_FLOAT_LABEL = calc_label_from_name('drawing a float')


def exponent_key(e):
    if e == MAX_EXPONENT:
        return float('inf')
    unbiased = e - BIAS
    if unbiased < 0:
        return 10000 - unbiased
    else:
        return unbiased


ENCODING_TABLE = array('H', sorted(hrange(MAX_EXPONENT + 1), key=exponent_key))
DECODING_TABLE = array('H', [0]) * len(ENCODING_TABLE)
try:
    from typing import Any, List, Callable, TypeVar, Generic, Optional  # noqa

    Ex = TypeVar("Ex", covariant=True)
    T = TypeVar("T")

    from hypothesis._settings import UniqueIdentifier  # noqa
    from hypothesis.internal.conjecture.data import ConjectureData  # noqa

except ImportError:  # pragma: no cover
    Ex = "key"  # type: ignore
    Generic = {Ex: object}  # type: ignore

calculating = UniqueIdentifier("calculating")

MAPPED_SEARCH_STRATEGY_DO_DRAW_LABEL = calc_label_from_name(
    "another attempted draw in MappedSearchStrategy")


def one_of_strategies(xs):
    """Helper function for unioning multiple strategies."""
    xs = tuple(xs)
    if not xs:
        raise ValueError("Cannot join an empty list of strategies")
    return OneOfStrategy(xs)


class SearchStrategy(Generic[Ex]):
    """A SearchStrategy is an object that knows how to explore data of a given
    type.

    Except where noted otherwise, methods on this class are not part of
    Status,
)
from hypothesis.internal.conjecture.engine import (
    MIN_TEST_CALLS,
    ConjectureRunner,
    ExitReason,
    TargetSelector,
)
from hypothesis.internal.conjecture.shrinker import Shrinker, block_program
from hypothesis.internal.conjecture.shrinking import Float
from hypothesis.internal.conjecture.utils import Sampler, calc_label_from_name
from hypothesis.internal.entropy import deterministic_PRNG
from tests.common.strategies import SLOW, HardToShrink
from tests.common.utils import no_shrink

SOME_LABEL = calc_label_from_name("some label")

TEST_SETTINGS = settings(
    max_examples=5000,
    buffer_size=1024,
    database=None,
    suppress_health_check=HealthCheck.all(),
)


def run_to_data(f):
    with deterministic_PRNG():
        runner = ConjectureRunner(f, settings=TEST_SETTINGS)
        runner.run()
        assert runner.interesting_examples
        last_data, = runner.interesting_examples.values()
Example #9
0
# Most of this work is copyright (C) 2013-2020 David R. MacIver
# ([email protected]), but it contains contributions by others. See
# CONTRIBUTING.rst for a full list of people who may hold copyright, and
# consult the git log if you need to determine who owns an individual
# contribution.
#
# 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/.
#
# END HEADER

from hypothesis.internal.conjecture import utils as cu
from hypothesis.strategies._internal.strategies import SearchStrategy

FEATURE_LABEL = cu.calc_label_from_name("feature flag")


class FeatureFlags:
    """Object that can be used to control a number of feature flags for a
    given test run.

    This enables an approach to data generation called swarm testing (
    see Groce, Alex, et al. "Swarm testing." Proceedings of the 2012
    International Symposium on Software Testing and Analysis. ACM, 2012), in
    which generation is biased by selectively turning some features off for
    each test case generated. When there are many interacting features this can
    find bugs that a pure generation strategy would otherwise have missed.

    FeatureFlags are designed to "shrink open", so that during shrinking they
    become less restrictive. This allows us to potentially shrink to smaller
from random import Random
import random
import base64
import json
from contextlib import contextmanager
import signal
import hashlib
import traceback
import click
from hypothesis.internal.conjecture.shrinker import block_program
import time
import re

NUMERALS = re.compile("[0-9]+")

STEP_LABEL = calc_label_from_name("TSTL STEP")
DRAW_STEP = calc_label_from_name("TSTL STEP SELECTION")


class TimeoutExpired(Exception):
    pass


@contextmanager
def timeout(seconds):
    def raiseexc(signum, frame):
        raise TimeoutExpired()

    start = time.monotonic()
    prev = None
    try:
Example #11
0
    next_up,
    next_up_normal,
    width_smallest_normals,
)
from hypothesis.internal.validation import (
    check_type,
    check_valid_bound,
    check_valid_interval,
)
from hypothesis.strategies._internal.misc import just, nothing
from hypothesis.strategies._internal.strategies import SearchStrategy
from hypothesis.strategies._internal.utils import cacheable, defines_strategy

# See https://github.com/python/mypy/issues/3186 - numbers.Real is wrong!
Real = Union[int, float, Fraction, Decimal]
ONE_BOUND_INTEGERS_LABEL = d.calc_label_from_name(
    "trying a one-bound int allowing 0")


class IntegersStrategy(SearchStrategy):
    def __init__(self, start, end):
        assert isinstance(start, int) or start is None
        assert isinstance(end, int) or end is None
        assert start is None or end is None or start <= end
        self.start = start
        self.end = end

    def __repr__(self):
        if self.start is None and self.end is None:
            return "integers()"
        if self.end is None:
            return f"integers(min_value={self.start})"
    Status,
)
from hypothesis.internal.conjecture.engine import (
    MIN_TEST_CALLS,
    ConjectureRunner,
    ExitReason,
    TargetSelector,
)
from hypothesis.internal.conjecture.shrinker import Shrinker, block_program
from hypothesis.internal.conjecture.shrinking import Float
from hypothesis.internal.conjecture.utils import Sampler, calc_label_from_name
from hypothesis.internal.entropy import deterministic_PRNG
from tests.common.strategies import SLOW, HardToShrink
from tests.common.utils import no_shrink

SOME_LABEL = calc_label_from_name("some label")


TEST_SETTINGS = settings(
    max_examples=5000,
    buffer_size=1024,
    database=None,
    suppress_health_check=HealthCheck.all(),
)


def run_to_data(f):
    with deterministic_PRNG():
        runner = ConjectureRunner(f, settings=TEST_SETTINGS)
        runner.run()
        assert runner.interesting_examples
Example #13
0
try:
    from random import Random  # noqa
    from typing import List, Callable, TypeVar, Generic, Optional  # noqa
    Ex = TypeVar('Ex', covariant=True)
    T = TypeVar('T')

    from hypothesis.internal.conjecture.data import ConjectureData  # noqa

except ImportError:  # pragma: no cover
    Ex = 'key'  # type: ignore
    Generic = {Ex: object}  # type: ignore

calculating = UniqueIdentifier('calculating')

MAPPED_SEARCH_STRATEGY_DO_DRAW_LABEL = calc_label_from_name(
    'another attempted draw in MappedSearchStrategy')


def one_of_strategies(xs):
    """Helper function for unioning multiple strategies."""
    xs = tuple(xs)
    if not xs:
        raise ValueError('Cannot join an empty list of strategies')
    return OneOfStrategy(xs)


class SearchStrategy(Generic[Ex]):
    """A SearchStrategy is an object that knows how to explore data of a given
    type.

    Except where noted otherwise, methods on this class are not part of
Example #14
0
from hypothesis.errors import Flaky, NoSuchExample, InvalidDefinition, \
    HypothesisException
from hypothesis.control import BuildContext
from hypothesis._settings import Verbosity
from hypothesis._settings import settings as Settings
from hypothesis.reporting import report, verbose_report, current_verbosity
from hypothesis.strategies import just, one_of, runner, tuples, \
    fixed_dictionaries
from hypothesis.vendor.pretty import CUnicodeIO, RepresentationPrinter
from hypothesis.internal.reflection import proxies, nicerepr
from hypothesis.internal.conjecture.data import StopTest
from hypothesis.internal.conjecture.utils import integer_range, \
    calc_label_from_name
from hypothesis.searchstrategy.strategies import SearchStrategy

STATE_MACHINE_RUN_LABEL = calc_label_from_name('another state machine step')

if False:
    from typing import Any, Dict, List, Text  # noqa


class TestCaseProperty(object):  # pragma: no cover
    def __get__(self, obj, typ=None):
        if obj is not None:
            typ = type(obj)
        return typ._to_test_case()

    def __set__(self, obj, value):
        raise AttributeError(u'Cannot set TestCase')

    def __delete__(self, obj):
       low k bits, where k is 52 - unbiased exponent.

The low bits correspond to the fractional part of the floating point number.
Reversing it bitwise means that we try to minimize the low bits, which kills
off the higher powers of 2 in the fraction first.
"""


MAX_EXPONENT = 0x7FF

SPECIAL_EXPONENTS = (0, MAX_EXPONENT)

BIAS = 1023
MAX_POSITIVE_EXPONENT = MAX_EXPONENT - 1 - BIAS

DRAW_FLOAT_LABEL = calc_label_from_name("drawing a float")


def exponent_key(e):
    if e == MAX_EXPONENT:
        return float("inf")
    unbiased = e - BIAS
    if unbiased < 0:
        return 10000 - unbiased
    else:
        return unbiased


ENCODING_TABLE = array("H", sorted(hrange(MAX_EXPONENT + 1), key=exponent_key))
DECODING_TABLE = array("H", [0]) * len(ENCODING_TABLE)
Example #16
0
        1.175494351e-38,
        2.2250738585072014e-308,
        1.7976931348623157e308,
        3.402823466e38,
        9007199254740992,
        1 - 10e-6,
        2 + 10e-6,
        1.192092896e-07,
        2.2204460492503131e-016,
    ] + [math.inf, math.nan] * 5,
    key=flt.float_to_lex,
)
NASTY_FLOATS = list(map(float, NASTY_FLOATS))
NASTY_FLOATS.extend([-x for x in NASTY_FLOATS])

FLOAT_STRATEGY_DO_DRAW_LABEL = calc_label_from_name(
    "getting another float in FloatStrategy")


class FloatStrategy(SearchStrategy):
    """Generic superclass for strategies which produce floats."""
    def __init__(self, allow_infinity, allow_nan, width):
        SearchStrategy.__init__(self)
        assert isinstance(allow_infinity, bool)
        assert isinstance(allow_nan, bool)
        assert width in (16, 32, 64)
        self.allow_infinity = allow_infinity
        self.allow_nan = allow_nan
        self.width = width

        self.nasty_floats = [
            float_of(f, self.width) for f in NASTY_FLOATS if self.permitted(f)
Example #17
0
    Verbosity,
    note_deprecation,
    settings as Settings,
)
from hypothesis.control import current_build_context
from hypothesis.core import given
from hypothesis.errors import InvalidArgument, InvalidDefinition
from hypothesis.internal.compat import hrange, quiet_raise, string_types
from hypothesis.internal.reflection import function_digest, nicerepr, proxies, qualname
from hypothesis.internal.validation import check_type
from hypothesis.reporting import current_verbosity, report
from hypothesis.searchstrategy.featureflags import FeatureStrategy
from hypothesis.searchstrategy.strategies import OneOfStrategy, SearchStrategy
from hypothesis.vendor.pretty import CUnicodeIO, RepresentationPrinter

STATE_MACHINE_RUN_LABEL = cu.calc_label_from_name("another state machine step")

if False:
    from typing import Any, Dict, List, Text  # noqa


class TestCaseProperty(object):  # pragma: no cover
    def __get__(self, obj, typ=None):
        if obj is not None:
            typ = type(obj)
        return typ._to_test_case()

    def __set__(self, obj, value):
        raise AttributeError(u"Cannot set TestCase")

    def __delete__(self, obj):
Example #18
0
from hypothesis.errors import Frozen, InvalidArgument, StopTest
from hypothesis.internal.compat import (
    benchmark_time,
    bit_length,
    hbytes,
    hrange,
    int_from_bytes,
    int_to_bytes,
    text_type,
    unicode_safe_repr,
)
from hypothesis.internal.conjecture.junkdrawer import IntList
from hypothesis.internal.conjecture.utils import calc_label_from_name
from hypothesis.internal.escalation import mark_for_escalation

TOP_LABEL = calc_label_from_name("top")
DRAW_BYTES_LABEL = calc_label_from_name("draw_bytes() in ConjectureData")


class ExtraInformation(object):
    """A class for holding shared state on a ``ConjectureData`` that should
    be added to the final ``ConjectureResult``."""
    def __repr__(self):
        return "ExtraInformation(%s)" % (", ".join(
            ["%s=%r" % (k, v) for k, v in self.__dict__.items()]), )

    def has_information(self):
        return bool(self.__dict__)


class Status(IntEnum):
Example #19
0
    combine_labels,
)
from hypothesis.internal.coverage import check_function
from hypothesis.internal.lazyformat import lazyformat
from hypothesis.internal.reflection import get_pretty_function_description
from hypothesis.utils.conventions import UniqueIdentifier

Ex = TypeVar("Ex", covariant=True)
T = TypeVar("T")
T3 = TypeVar("T3")
T4 = TypeVar("T4")
T5 = TypeVar("T5")

calculating = UniqueIdentifier("calculating")

MAPPED_SEARCH_STRATEGY_DO_DRAW_LABEL = calc_label_from_name(
    "another attempted draw in MappedSearchStrategy")

FILTERED_SEARCH_STRATEGY_DO_DRAW_LABEL = calc_label_from_name(
    "single loop iteration in FilteredStrategy")


def recursive_property(name, default):
    """Handle properties which may be mutually recursive among a set of
    strategies.

    These are essentially lazily cached properties, with the ability to set
    an override: If the property has not been explicitly set, we calculate
    it on first access and memoize the result for later.

    The problem is that for properties that depend on each other, a naive
    calculation strategy may hit infinite recursion. Consider for example
from hypothesis import Phase, Verbosity, HealthCheck, settings, unlimited
from hypothesis.errors import FailedHealthCheck
from tests.common.utils import no_shrink, checks_deprecated_behaviour
from hypothesis.database import ExampleDatabase, InMemoryExampleDatabase
from tests.common.strategies import SLOW, HardToShrink
from hypothesis.internal.compat import hbytes, hrange, int_from_bytes
from hypothesis.internal.entropy import deterministic_PRNG
from hypothesis.internal.conjecture.data import MAX_DEPTH, Status, \
    ConjectureData
from hypothesis.internal.conjecture.utils import Sampler, \
    calc_label_from_name
from hypothesis.internal.conjecture.engine import Shrinker, ExitReason, \
    RunIsComplete, TargetSelector, ConjectureRunner, PassClassification, \
    sort_key, block_program

SOME_LABEL = calc_label_from_name('some label')


def run_to_buffer(f):
    with deterministic_PRNG():
        runner = ConjectureRunner(f, settings=settings(
            max_examples=5000, buffer_size=1024,
            database=None, suppress_health_check=HealthCheck.all(),
        ))
        runner.run()
        assert runner.interesting_examples
        last_data, = runner.interesting_examples.values()
        return hbytes(last_data.buffer)


def test_can_index_results():
Example #21
0
from __future__ import division, print_function, absolute_import

import sys
from enum import IntEnum

import attr

from hypothesis.errors import Frozen, StopTest, InvalidArgument
from hypothesis.internal.compat import hbytes, hrange, text_type, \
    bit_length, benchmark_time, int_from_bytes, unicode_safe_repr
from hypothesis.internal.coverage import IN_COVERAGE_TESTS
from hypothesis.internal.escalation import mark_for_escalation
from hypothesis.internal.conjecture.utils import calc_label_from_name

TOP_LABEL = calc_label_from_name('top')
DRAW_BYTES_LABEL = calc_label_from_name('draw_bytes() in ConjectureData')


class Status(IntEnum):
    OVERRUN = 0
    INVALID = 1
    VALID = 2
    INTERESTING = 3

    def __repr__(self):
        return 'Status.%s' % (self.name,)


@attr.s(slots=True)
class Example(object):
Example #22
0
    function_digest,
    nicerepr,
    proxies,
    qualname,
)
from hypothesis.internal.validation import check_type
from hypothesis.reporting import current_verbosity, report
from hypothesis.strategies._internal.featureflags import FeatureStrategy
from hypothesis.strategies._internal.strategies import (
    OneOfStrategy,
    SearchStrategy,
    check_strategy,
)
from hypothesis.vendor.pretty import RepresentationPrinter

STATE_MACHINE_RUN_LABEL = cu.calc_label_from_name("another state machine step")
SHOULD_CONTINUE_LABEL = cu.calc_label_from_name("should we continue drawing")


class TestCaseProperty:  # pragma: no cover
    def __get__(self, obj, typ=None):
        if obj is not None:
            typ = type(obj)
        return typ._to_test_case()

    def __set__(self, obj, value):
        raise AttributeError("Cannot set TestCase")

    def __delete__(self, obj):
        raise AttributeError("Cannot delete TestCase")
Example #23
0
from hypothesis.errors import Frozen, InvalidArgument, StopTest
from hypothesis.internal.compat import (
    benchmark_time,
    bit_length,
    hbytes,
    hrange,
    int_from_bytes,
    int_to_bytes,
    text_type,
    unicode_safe_repr,
)
from hypothesis.internal.conjecture.junkdrawer import IntList
from hypothesis.internal.conjecture.utils import calc_label_from_name
from hypothesis.internal.escalation import mark_for_escalation

TOP_LABEL = calc_label_from_name("top")
DRAW_BYTES_LABEL = calc_label_from_name("draw_bytes() in ConjectureData")


class ExtraInformation(object):
    """A class for holding shared state on a ``ConjectureData`` that should
    be added to the final ``ConjectureResult``."""

    def __repr__(self):
        return "ExtraInformation(%s)" % (
            ", ".join(["%s=%r" % (k, v) for k, v in self.__dict__.items()]),
        )

    def has_information(self):
        return bool(self.__dict__)