예제 #1
0
import threading
from enum import Enum, IntEnum, unique

import attr

from hypothesis.errors import InvalidArgument, HypothesisDeprecationWarning
from hypothesis.configuration import hypothesis_home_dir
from hypothesis.internal.compat import PYPY
from hypothesis.utils.conventions import UniqueIdentifier, not_set
from hypothesis.utils.dynamicvariables import DynamicVariable

__all__ = [
    'settings',
]

unlimited = UniqueIdentifier('unlimited')

all_settings = {}

_db_cache = {}


class settingsProperty(object):
    def __init__(self, name, show_default):
        self.name = name
        self.show_default = show_default

    def __get__(self, obj, type=None):
        if obj is None:
            return self
        else:
예제 #2
0
import hashlib
from collections import defaultdict

import hypothesis.internal.conjecture.utils as cu
from hypothesis.errors import NoExamples, NoSuchExample, Unsatisfiable, \
    UnsatisfiedAssumption
from hypothesis.control import assume, reject, _current_build_context
from hypothesis._settings import note_deprecation
from hypothesis.internal.compat import hrange, qualname, bit_length, \
    str_to_bytes, int_from_bytes
from hypothesis.utils.conventions import UniqueIdentifier
from hypothesis.internal.lazyformat import lazyformat
from hypothesis.internal.reflection import get_pretty_function_description

calculating = UniqueIdentifier('calculating')

LABEL_MASK = 2**64 - 1


def calc_label(cls):
    name = str_to_bytes(qualname(cls))
    hashed = hashlib.md5(name).digest()
    return int_from_bytes(hashed[:8])


def combine_labels(*labels):
    label = 0
    for l in labels:
        label = (label << 1) & LABEL_MASK
        label ^= l
예제 #3
0
from hypothesis.utils.conventions import UniqueIdentifier

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]):
from hypothesis.utils.conventions import UniqueIdentifier

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
예제 #5
0
파일: data.py 프로젝트: wasobi/hypothesis
    def __attrs_post_init__(self):
        self.index = len(self.buffer)

    @property
    def examples(self):
        if self.__examples is None:
            self.__examples = calc_examples(self)
            self.example_boundaries = None

        assert self.example_boundaries is None
        return self.__examples


# Special "labels" used to indicate the end of example boundaries
Stop = UniqueIdentifier("Stop")
StopDiscard = UniqueIdentifier("StopDiscard")


class ConjectureData(object):
    @classmethod
    def for_buffer(self, buffer):
        buffer = hbytes(buffer)
        return ConjectureData(
            max_length=len(buffer),
            draw_bytes=lambda data, n: hbytes(buffer[data.index:data.index + n]
                                              ),
        )

    def __init__(self, max_length, draw_bytes):
        self.max_length = max_length
예제 #6
0
            sqlite_delta = timedelta(microseconds=2**47 - 1)
            __default_field_mappings.update({
                dm.TimeField:
                st.times(),
                dm.DurationField:
                st.timedeltas(-sqlite_delta, sqlite_delta),
            })

    return __default_field_mappings


def add_default_field_mapping(field_type, strategy):
    field_mappings()[field_type] = strategy


default_value = UniqueIdentifier(u'default_value')


def validator_to_filter(f):
    """Converts the field run_validators method to something suitable for use
    in filter."""
    def validate(value):
        try:
            f.run_validators(value)
            return True
        except ValidationError:
            return False

    return validate

예제 #7
0
    HypothesisDeprecationWarning,
    InvalidArgument,
    InvalidState,
)
from hypothesis.internal.compat import integer_types, quiet_raise, string_types
from hypothesis.internal.reflection import get_pretty_function_description
from hypothesis.internal.validation import check_type, try_convert
from hypothesis.utils.conventions import UniqueIdentifier, not_set
from hypothesis.utils.dynamicvariables import DynamicVariable

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

__all__ = ["settings"]

unlimited = UniqueIdentifier("unlimited")

all_settings = {}  # type: Dict[str, Setting]


class settingsProperty(object):
    def __init__(self, name, show_default):
        self.name = name
        self.show_default = show_default

    def __get__(self, obj, type=None):
        if obj is None:
            return self
        else:
            try:
                result = obj.__dict__[self.name]
def test_unique_identifier_repr():
    assert repr(UniqueIdentifier(u'hello_world')) == u'hello_world'
def test_unique_identifier_repr():
    assert repr(UniqueIdentifier("hello_world")) == "hello_world"
예제 #10
0
        self.tag = tag


NEGATED_CACHE = {}


def negated(tag):
    try:
        return NEGATED_CACHE[tag]
    except KeyError:
        result = Negated(tag)
        NEGATED_CACHE[tag] = result
        return result


universal = UniqueIdentifier('universal')


class TargetSelector(object):
    """Data structure for selecting targets to use for mutation.

    The goal is to do a good job of exploiting novelty in examples without
    getting too obsessed with any particular novel factor.

    Roughly speaking what we want to do is give each distinct coverage target
    equal amounts of time. However some coverage targets may be harder to fuzz
    than others, or may only appear in a very small minority of examples, so we
    don't want to let those dominate the testing.

    Targets are selected according to the following rules: