def problem(draw):
    b = hbytes(draw(st.binary(min_size=1, max_size=8)))
    m = int_from_bytes(b) * 256
    assume(m > 0)
    marker = draw(st.binary(max_size=8))
    bound = draw(st.integers(0, m - 1))
    return (b, marker, bound)
def array_values(draw):
    matching = draw(st.lists(elements=st.binary(min_size=2, max_size=2), min_size=1))
    non_matching = draw(
        st.lists(
            elements=st.binary(min_size=2, max_size=2),
            min_size=1).filter(lambda x: x != matching))
    return (matching, non_matching)
示例#3
0
文件: test_prf.py 项目: ashfall/tls
def prf_given():
    """
    A wrapper for :py:func:`hypothesis.given` that establishes
    parameters common to all Pseudo-Random Function tests.

    :return: The same opaque type returned by
             :py:func:`hypothesis.given`
    """
    _prf_given = given(secret=st.binary(max_size=4096),
                       label=ascii_bytes(min_size=1, max_size=1024),
                       # OpenSSL does not use seeds longer than 1024 bytes
                       seed=st.binary(max_size=1024),
                       hash_cls=st.sampled_from([
                           hashes.SHA1,
                           hashes.SHA224,
                           hashes.SHA256,
                           hashes.SHA384,
                           hashes.SHA512,
                           hashes.RIPEMD160,
                           hashes.Whirlpool,
                           hashes.MD5,
                       ]),
                       output_length=st.integers(min_value=0, max_value=1024))

    def _ignore_slow_and_large_prf_given(function):
        """
        Suppress data generation and size speed checks.
        """
        ignore_slow = settings(suppress_health_check=[
            HealthCheck.data_too_large,
            HealthCheck.too_slow,
        ])
        return ignore_slow(_prf_given(function))

    return _ignore_slow_and_large_prf_given
def test_binary_respects_changes_in_size():
    @given(binary())
    def test_foo(x):
        assert len(x) <= 10
    with pytest.raises(AssertionError):
        test_foo()

    @given(binary(max_size=10))
    def test_foo(x):
        assert len(x) <= 10
    test_foo()
示例#5
0
文件: utils.py 项目: EdgarChen/servo
def simple_attrs_with_metadata(draw):
    """
    Create a simple attribute with arbitrary metadata.
    """
    c_attr = draw(simple_attrs)
    keys = st.booleans() | st.binary() | st.integers() | st.text()
    vals = st.booleans() | st.binary() | st.integers() | st.text()
    metadata = draw(st.dictionaries(keys=keys, values=vals))

    return attr.ib(c_attr._default, c_attr._validator, c_attr.repr,
                   c_attr.cmp, c_attr.hash, c_attr.init, c_attr.convert,
                   metadata)
def regex_strategy(regex, fullmatch):
    if not hasattr(regex, "pattern"):
        regex = re.compile(regex)

    is_unicode = isinstance(regex.pattern, text_type)

    parsed = sre_parse.parse(regex.pattern, flags=regex.flags)

    if not parsed:
        if is_unicode:
            return st.text()
        else:
            return st.binary()

    if is_unicode:
        base_padding_strategy = st.text()
        empty = st.just(u"")
        newline = st.just(u"\n")
    else:
        base_padding_strategy = st.binary()
        empty = st.just(b"")
        newline = st.just(b"\n")

    right_pad = base_padding_strategy
    left_pad = base_padding_strategy

    if fullmatch:
        right_pad = empty
    elif parsed[-1][0] == sre.AT:
        if parsed[-1][1] == sre.AT_END_STRING:
            right_pad = empty
        elif parsed[-1][1] == sre.AT_END:
            if regex.flags & re.MULTILINE:
                right_pad = st.one_of(
                    empty, st.builds(operator.add, newline, right_pad)
                )
            else:
                right_pad = st.one_of(empty, newline)
    if fullmatch:
        left_pad = empty
    elif parsed[0][0] == sre.AT:
        if parsed[0][1] == sre.AT_BEGINNING_STRING:
            left_pad = empty
        elif parsed[0][1] == sre.AT_BEGINNING:
            if regex.flags & re.MULTILINE:
                left_pad = st.one_of(empty, st.builds(operator.add, left_pad, newline))
            else:
                left_pad = empty

    base = base_regex_strategy(regex, parsed).filter(regex.search)

    return maybe_pad(regex, base, left_pad, right_pad)
 def steps(self):
     if self.state == self.STATE_EMPTY:
         attrs = {
             'keys': st.lists(st.binary(), min_size=2, max_size=5, unique=True),
             'fields': st.lists(st.binary(), min_size=2, max_size=5, unique=True),
             'values': st.lists(st.binary() | int_as_bytes | float_as_bytes,
                                min_size=2, max_size=5, unique=True),
             'scores': st.lists(st.floats(width=32), min_size=2, max_size=5, unique=True)
         }
         return st.fixed_dictionaries(attrs)
     elif self.state == self.STATE_INIT:
         return st.lists(self.create_command_strategy)
     else:
         return self.command_strategy
def fake_node_pems():
    # These are totally bogus but they're quick to generate.
    return strategies.builds(
        lambda cert, key: u"".join([
            u"-----BEGIN CERTIFICATE-----\n",
            cert.encode("base64"),
            u"-----END CERTIFICATE-----\n",
            u"-----BEGIN RSA PRIVATE KEY-----\n",
            key.encode("base64"),
            u"-----END RSA PRIVATE KEY-----\n",
        ]),
        cert=strategies.binary(min_size=256, max_size=256),
        key=strategies.binary(min_size=256, max_size=256),
    )
示例#9
0
def pem_objects(draw):
    """
    Strategy for generating ``pem`` objects.
    """
    key = RSAPrivateKey((
        b'-----BEGIN RSA PRIVATE KEY-----\n' +
        encodebytes(draw(s.binary(min_size=1))) +
        b'-----END RSA PRIVATE KEY-----\n'))
    return [key] + [
        Certificate((
            b'-----BEGIN CERTIFICATE-----\n' +
            encodebytes(cert) +
            b'-----END CERTIFICATE-----\n'))
        for cert in draw(s.lists(s.binary(min_size=1), min_size=1))]
def swissnum():
    return strategies.binary(
        min_size=Tub.NAMEBITS / 8,
        max_size=Tub.NAMEBITS / 8,
    ).map(
        lambda b: b32encode(b).rstrip("=").lower()
    )
def test_saves_incremental_steps_in_database():
    key = b"a database key"
    database = InMemoryExampleDatabase()
    find(
        st.binary(min_size=10), lambda x: has_a_non_zero_byte(x),
        settings=settings(database=database), database_key=key
    )
    assert len(all_values(database)) > 1
def test_saves_incremental_steps_in_database():
    key = b"a database key"
    database = SQLiteExampleDatabase(':memory:')
    find(
        st.binary(min_size=10), lambda x: any(x),
        settings=settings(database=database), database_key=key
    )
    assert len(set(database.fetch(key))) > 1
def test_large_data_will_fail_a_health_check():
    @given(st.lists(st.binary(min_size=1024, max_size=1024), average_size=100))
    @settings(database=None, buffer_size=1000)
    def test(x):
        pass

    with raises(FailedHealthCheck) as e:
        test()
    assert 'allowable size' in e.value.args[0]
def test_large_data_will_fail_a_health_check():
    @given(st.none() | st.binary(min_size=1024))
    @settings(database=None, buffer_size=1000)
    def test(x):
        pass

    with raises(FailedHealthCheck) as e:
        test()
    assert "allowable size" in e.value.args[0]
def test_large_base_example_fails_health_check():
    @given(st.binary(min_size=7000, max_size=7000))
    def test(b):
        pass

    with pytest.raises(FailedHealthCheck) as exc:
        test()

    assert exc.value.health_check == HealthCheck.large_base_example
def test_example_that_shrinks_to_overrun_fails_health_check():
    @given(st.binary(min_size=9000, max_size=9000) | st.none())
    def test(b):
        pass

    with pytest.raises(FailedHealthCheck) as exc:
        test()

    assert exc.value.health_check == HealthCheck.large_base_example
 def stuff():
     try:
         find(
             st.binary(min_size=50), lambda x: do_we_care and any(x),
             settings=settings(database=database, max_examples=10),
             database_key=key
         )
     except NoSuchExample:
         pass
 def stuff():
     try:
         find(
             st.binary(min_size=100), check,
             settings=settings(database=database, max_examples=10),
             database_key=key
         )
     except NoSuchExample:
         pass
 def stuff():
     try:
         find(
             st.binary(min_size=100),
             lambda x: assume(not finicky) and any(x),
             settings=settings(database=database, timeout=5),
             database_key=key
         )
     except Unsatisfiable:
         pass
 def stuff():
     try:
         find(
             st.binary(min_size=100),
             lambda x: assume(not finicky) and has_a_non_zero_byte(x),
             settings=settings(database=database, max_shrinks=10),
             database_key=key
         )
     except Unsatisfiable:
         pass
def test_minimize_one_of_distinct_types():
    y = booleans() | binary()
    x = minimal(
        tuples(y, y),
        lambda x: type(x[0]) != type(x[1])
    )
    assert x in (
        (False, b''),
        (b'', False)
    )
示例#22
0
def ann2strategy(s_value):
    if isinstance(s_value, SomeChar):
        return builds(chr, integers(min_value=0, max_value=255))
    elif isinstance(s_value, SomeString):
        if s_value.can_be_None:
            return binary() | just(None)
        else:
            return binary()
    elif isinstance(s_value, SomeUnicodeCodePoint):
        return characters()
    elif isinstance(s_value, SomeUnicodeString):
        if s_value.can_be_None:
            return text() | just(None)
        else:
            return text()
    elif isinstance(s_value, SomeInteger):
        return integers(min_value=~sys.maxint, max_value=sys.maxint)
    else:
        raise TypeError("Cannot convert annotation %s to a strategy" % s_value)
示例#23
0
def from_dtype(dtype):
    # type: (np.dtype) -> st.SearchStrategy[Any]
    """Creates a strategy which can generate any value of the given dtype."""
    check_type(np.dtype, dtype, 'dtype')
    # Compound datatypes, eg 'f4,f4,f4'
    if dtype.names is not None:
        # mapping np.void.type over a strategy is nonsense, so return now.
        return st.tuples(
            *[from_dtype(dtype.fields[name][0]) for name in dtype.names])

    # Subarray datatypes, eg '(2, 3)i4'
    if dtype.subdtype is not None:
        subtype, shape = dtype.subdtype
        return arrays(subtype, shape)

    # Scalar datatypes
    if dtype.kind == u'b':
        result = st.booleans()  # type: SearchStrategy[Any]
    elif dtype.kind == u'f':
        if dtype.itemsize == 2:
            result = st.floats(width=16)
        elif dtype.itemsize == 4:
            result = st.floats(width=32)
        else:
            result = st.floats()
    elif dtype.kind == u'c':
        if dtype.itemsize == 8:
            float32 = st.floats(width=32)
            result = st.builds(complex, float32, float32)
        else:
            result = st.complex_numbers()
    elif dtype.kind in (u'S', u'a'):
        # Numpy strings are null-terminated; only allow round-trippable values.
        # `itemsize == 0` means 'fixed length determined at array creation'
        result = st.binary(max_size=dtype.itemsize or None
                           ).filter(lambda b: b[-1:] != b'\0')
    elif dtype.kind == u'u':
        result = st.integers(min_value=0,
                             max_value=2 ** (8 * dtype.itemsize) - 1)
    elif dtype.kind == u'i':
        overflow = 2 ** (8 * dtype.itemsize - 1)
        result = st.integers(min_value=-overflow, max_value=overflow - 1)
    elif dtype.kind == u'U':
        # Encoded in UTF-32 (four bytes/codepoint) and null-terminated
        result = st.text(max_size=(dtype.itemsize or 0) // 4 or None
                         ).filter(lambda b: b[-1:] != u'\0')
    elif dtype.kind in (u'm', u'M'):
        if '[' in dtype.str:
            res = st.just(dtype.str.split('[')[-1][:-1])
        else:
            res = st.sampled_from(TIME_RESOLUTIONS)
        result = st.builds(dtype.type, st.integers(-2**63, 2**63 - 1), res)
    else:
        raise InvalidArgument(u'No strategy inference for {}'.format(dtype))
    return result.map(dtype.type)
def test_raises_invalid_if_wrong_version():
    b = b'hello world'
    n = len(b)

    @reproduce_failure('1.0.0', encode_failure(b))
    @given(st.binary(min_size=n, max_size=n))
    def test(x):
        pass

    with pytest.raises(InvalidArgument):
        test()
def test_reproduces_the_failure():
    b = b'hello world'
    n = len(b)

    @reproduce_failure(__version__, encode_failure(b))
    @given(st.binary(min_size=n, max_size=n))
    def test(x):
        assert x != b

    with pytest.raises(AssertionError):
        test()
def test_errors_if_provided_example_does_not_reproduce_failure():
    b = b'hello world'
    n = len(b)

    @reproduce_failure(__version__, encode_failure(b))
    @given(st.binary(min_size=n, max_size=n))
    def test(x):
        assert x == b

    with pytest.raises(DidNotReproduce):
        test()
def test_errors_with_did_not_reproduce_if_the_shape_changes():
    b = b'hello world'
    n = len(b)

    @reproduce_failure(__version__, encode_failure(b))
    @given(st.binary(min_size=n + 1, max_size=n + 1))
    def test(x):
        assert x == b

    with pytest.raises(DidNotReproduce):
        test()
def test_errors_with_did_not_reproduce_if_rejected():
    b = b'hello world'
    n = len(b)

    @reproduce_failure(__version__, encode_failure(b))
    @given(st.binary(min_size=n, max_size=n))
    def test(x):
        reject()

    with pytest.raises(DidNotReproduce):
        test()
示例#29
0
def simple_attrs_with_metadata(draw):
    """
    Create a simple attribute with arbitrary metadata.
    """
    c_attr = draw(simple_attrs)
    keys = st.booleans() | st.binary() | st.integers() | st.text()
    vals = st.booleans() | st.binary() | st.integers() | st.text()
    metadata = draw(st.dictionaries(
        keys=keys, values=vals, min_size=1, max_size=5))

    return attr.ib(
        default=c_attr._default,
        validator=c_attr._validator,
        repr=c_attr.repr,
        cmp=c_attr.cmp,
        hash=c_attr.hash,
        init=c_attr.init,
        metadata=metadata,
        type=None,
        converter=c_attr.converter,
    )
def test_max_shrinks():
    seen = set()

    def tracktrue(s):
        seen.add(s)
        return True

    find(
        st.binary(min_size=100, max_size=100), tracktrue,
        settings=settings(max_shrinks=1)
    )
    assert len(seen) == 2
示例#31
0
def _for_binary(field):
    min_size, max_size = length_bounds_from_validators(field)
    if getattr(field, "blank", False) or not getattr(field, "required", True):
        return st.just(b"") | st.binary(min_size=min_size, max_size=max_size)
    return st.binary(min_size=min_size, max_size=max_size)
示例#32
0
def resolve_Match(thing):
    if thing.__args__[0] == bytes:
        return (st.binary(min_size=1).map(
            lambda c: re.match(b".", c, flags=re.DOTALL)).filter(bool))
    return st.text().map(lambda c: re.match(".", c, flags=re.DOTALL)).filter(
        bool)
示例#33
0

def test_value_error_y(all_zero_3_byte_object_data,
                       all_zero_4_byte_object_data):
    # GIVEN data for 3 and 4 byte objects, where everything is set to 0

    # WHEN illegal values are encoded in the data
    bad_y_3_byte = all_zero_3_byte_object_data.copy()
    bad_y_3_byte[0] |= MAX_Y_VALUE + 1

    bad_y_4_byte = all_zero_4_byte_object_data.copy()
    bad_y_4_byte[0] |= MAX_Y_VALUE + 1

    # THEN a ValueError is raised
    for bad_data in [bad_y_3_byte, bad_y_4_byte]:
        with pytest.raises(ValueError,
                           match="Data designating y value cannot be"):
            LevelObject(bad_data)


def test_value_error():
    with pytest.raises(ValueError, match="Length of the given data"):
        LevelObject(bytearray(5))


@given(data=strategies.binary(
    min_size=3,
    max_size=4).filter(lambda data: valid_y_value_in_byte(data[0])))
def test_object_construction(data):
    LevelObject(data)
    """Raise ValueError when display_clock is called w/o a bool."""
    wrong_type = 42
    with expected_protocol(
            ik.tektronix.TekTDS5xx,
            [
            ],
            [
            ]
    ) as inst:
        with pytest.raises(ValueError) as err_info:
            inst.display_clock = wrong_type
        err_msg = err_info.value.args[0]
        assert err_msg == f"Expected bool but got {type(wrong_type)} instead"


@given(data=st.binary(min_size=1, max_size=2147483647))
def test_get_hardcopy(mocker, data):
    """Transfer data in binary from the instrument.

    Data is at least 1 byte long, then we need to add 8 for the
    color table.
    Fake the header of the data such that in byte 18:30 are 4 factorial
    packed as '<iihh' that multiplied together result in the length of
    the total data. Limit maximum size of binary such that we don't have
    to factor the length and such that it simply fits into 4 bytes
    unsigned.
    Take some random data, then stick a header to it. Unchecked entries
    in header are filled with zeros.
    Mocking out sleep to do nothing.
    """
    # mock out time
    builds, floats, one_of, booleans, integers, frozensets, sampled_from


@given(integers(), integers())
def test_int_addition_is_commutative(x, y):
    assert x + y == y + x


@fails
@given(text(), text())
def test_str_addition_is_commutative(x, y):
    assert x + y == y + x


@fails
@given(binary(), binary())
def test_bytes_addition_is_commutative(x, y):
    assert x + y == y + x


@given(integers(), integers(), integers())
def test_int_addition_is_associative(x, y, z):
    assert x + (y + z) == (x + y) + z


@fails
@given(floats(), floats(), floats())
@settings(
    max_examples=2000, )
def test_float_addition_is_associative(x, y, z):
    assert x + (y + z) == (x + y) + z
示例#36
0
def _strategy(codes, context, is_unicode):
    """Convert SRE regex parse tree to strategy that generates strings matching
    that regex represented by that parse tree.

    `codes` is either a list of SRE regex elements representations or a
    particular element representation. Each element is a tuple of element code
    (as string) and parameters. E.g. regex 'ab[0-9]+' compiles to following
    elements:

        [
            (LITERAL, 97),
            (LITERAL, 98),
            (MAX_REPEAT, (1, 4294967295, [
                (IN, [
                    (RANGE, (48, 57))
                ])
            ]))
        ]

    The function recursively traverses regex element tree and converts each
    element to strategy that generates strings that match that element.

    Context stores
    1. List of groups (for backreferences)
    2. Active regex flags (e.g. IGNORECASE, DOTALL, UNICODE, they affect
       behavior of various inner strategies)
    """

    def recurse(codes):
        return _strategy(codes, context, is_unicode)

    if is_unicode:
        empty = ""
        to_char = chr
    else:
        empty = b""
        to_char = int_to_byte
        binary_char = st.binary(min_size=1, max_size=1)

    if not isinstance(codes, tuple):
        # List of codes
        strategies = []

        i = 0
        while i < len(codes):
            if codes[i][0] == sre.LITERAL and not context.flags & re.IGNORECASE:
                # Merge subsequent "literals" into one `just()` strategy
                # that generates corresponding text if no IGNORECASE
                j = i + 1
                while j < len(codes) and codes[j][0] == sre.LITERAL:
                    j += 1

                if i + 1 < j:
                    chars = (to_char(charcode) for _, charcode in codes[i:j])
                    strategies.append(st.just(empty.join(chars)))
                    i = j
                    continue

            strategies.append(recurse(codes[i]))
            i += 1

        # We handle this separately at the top level, but some regex can
        # contain empty lists internally, so we need to handle this here too.
        if not strategies:
            return st.just(empty)

        if len(strategies) == 1:
            return strategies[0]
        return st.tuples(*strategies).map(empty.join)
    else:
        # Single code
        code, value = codes
        if code == sre.LITERAL:
            # Regex 'a' (single char)
            c = to_char(value)
            if (
                context.flags & re.IGNORECASE
                and c != c.swapcase()
                and re.match(re.escape(c), c.swapcase(), re.IGNORECASE) is not None
            ):
                # We do the explicit check for swapped-case matching because
                # eg 'ß'.upper() == 'SS' and ignorecase doesn't match it.
                return st.sampled_from([c, c.swapcase()])
            return st.just(c)

        elif code == sre.NOT_LITERAL:
            # Regex '[^a]' (negation of a single char)
            c = to_char(value)
            blacklist = {c}
            if (
                context.flags & re.IGNORECASE
                and re.match(re.escape(c), c.swapcase(), re.IGNORECASE) is not None
            ):
                # There are a few cases where .swapcase() returns two characters,
                # but is still a case-insensitive match.  In such cases we add *both*
                # characters to our blacklist, to avoid doing the wrong thing for
                # patterns such as r"[^\u0130]+" where "i\u0307" matches.
                #
                # (that's respectively 'Latin letter capital I with dot above' and
                # 'latin latter i' + 'combining dot above'; see issue #2657)
                #
                # As a final additional wrinkle, "latin letter capital I" *also*
                # case-insensitive-matches, with or without combining dot character.
                # We therefore have to chain .swapcase() calls until a fixpoint.
                stack = [c.swapcase()]
                while stack:
                    for char in stack.pop():
                        blacklist.add(char)
                        stack.extend(set(char.swapcase()) - blacklist)

            if is_unicode:
                return st.characters(blacklist_characters=blacklist)
            else:
                return binary_char.filter(lambda c: c not in blacklist)

        elif code == sre.IN:
            # Regex '[abc0-9]' (set of characters)
            negate = value[0][0] == sre.NEGATE
            if is_unicode:
                builder = CharactersBuilder(negate, context.flags)
            else:
                builder = BytesBuilder(negate, context.flags)

            for charset_code, charset_value in value:
                if charset_code == sre.NEGATE:
                    # Regex '[^...]' (negation)
                    # handled by builder = CharactersBuilder(...) above
                    pass
                elif charset_code == sre.LITERAL:
                    # Regex '[a]' (single char)
                    builder.add_char(charset_value)
                elif charset_code == sre.RANGE:
                    # Regex '[a-z]' (char range)
                    low, high = charset_value
                    for char_code in range(low, high + 1):
                        builder.add_char(char_code)
                elif charset_code == sre.CATEGORY:
                    # Regex '[\w]' (char category)
                    builder.add_category(charset_value)
                else:
                    # Currently there are no known code points other than
                    # handled here. This code is just future proofing
                    raise NotImplementedError("Unknown charset code: %s" % charset_code)
            return builder.strategy

        elif code == sre.ANY:
            # Regex '.' (any char)
            if is_unicode:
                if context.flags & re.DOTALL:
                    return st.characters()
                return st.characters(blacklist_characters="\n")
            else:
                if context.flags & re.DOTALL:
                    return binary_char
                return binary_char.filter(lambda c: c != b"\n")

        elif code == sre.AT:
            # Regexes like '^...', '...$', '\bfoo', '\Bfoo'
            # An empty string (or newline) will match the token itself, but
            # we don't and can't check the position (eg '%' at the end)
            return st.just(empty)

        elif code == sre.SUBPATTERN:
            # Various groups: '(...)', '(:...)' or '(?P<name>...)'
            old_flags = context.flags
            context.flags = (context.flags | value[1]) & ~value[2]

            strat = _strategy(value[-1], context, is_unicode)

            context.flags = old_flags

            if value[0]:
                strat = update_group(value[0], strat)

            return strat

        elif code == sre.GROUPREF:
            # Regex '\\1' or '(?P=name)' (group reference)
            return reuse_group(value)

        elif code == sre.ASSERT:
            # Regex '(?=...)' or '(?<=...)' (positive lookahead/lookbehind)
            return recurse(value[1])

        elif code == sre.ASSERT_NOT:
            # Regex '(?!...)' or '(?<!...)' (negative lookahead/lookbehind)
            return st.just(empty)

        elif code == sre.BRANCH:
            # Regex 'a|b|c' (branch)
            return st.one_of([recurse(branch) for branch in value[1]])

        elif code in [sre.MIN_REPEAT, sre.MAX_REPEAT]:
            # Regexes 'a?', 'a*', 'a+' and their non-greedy variants
            # (repeaters)
            at_least, at_most, subregex = value
            if at_most == sre.MAXREPEAT:
                at_most = None
            if at_least == 0 and at_most == 1:
                return st.just(empty) | recurse(subregex)
            return st.lists(recurse(subregex), min_size=at_least, max_size=at_most).map(
                empty.join
            )

        elif code == sre.GROUPREF_EXISTS:
            # Regex '(?(id/name)yes-pattern|no-pattern)'
            # (if group exists choice)
            return group_conditional(
                value[0],
                recurse(value[1]),
                recurse(value[2]) if value[2] else st.just(empty),
            )

        else:
            # Currently there are no known code points other than handled here.
            # This code is just future proofing
            raise NotImplementedError("Unknown code point: %s" % repr(code))
示例#37
0
    type_def = draw(message_typedef_gen())
    message = draw(gen_message_data(type_def))
    return type_def, message

# Map types to generators
input_map = {
    'fixed32': st.integers(min_value=0, max_value=(2**32)-1),
    'sfixed32': st.integers(min_value=-(2**16), max_value=2**16),
    'fixed64': st.integers(min_value=0, max_value=(2**64)-1),
    'sfixed64': st.integers(min_value=-(2**32), max_value=2**32),
    'float': st.floats(width=32, allow_nan=False),
    'double': st.floats(width=64, allow_nan=False),
    'uint': st.integers(min_value=0, max_value=2**63),
    'int': st.integers(min_value=-(2**63), max_value=2**63),
    'sint': st.integers(min_value=-(2**63), max_value=2**63),
    'bytes':  st.binary(),
    'string':  st.text(),
    'message':  gen_message(),
    'group': None
}
input_map.update({
    'packed_uint': st.lists(input_map['uint']),
    'packed_int': st.lists(input_map['int']),
    'packed_sint':st.lists(input_map['sint']),
    'packed_fixed32': st.lists(input_map['fixed32']),
    'packed_sfixed32': st.lists(input_map['sfixed32']),
    'packed_float': st.lists(input_map['float']),
    'packed_fixed64': st.lists(input_map['fixed64']),
    'packed_sfixed64': st.lists(input_map['sfixed64']),
    'packed_double': st.lists(input_map['double']),
})
示例#38
0
class TestGetsBasicModels(TestCase):
    @given(from_model(Company))
    def test_is_company(self, company):
        self.assertIsInstance(company, Company)
        self.assertIsNotNone(company.pk)

    @given(from_model(Store, company=from_model(Company)))
    def test_can_get_a_store(self, store):
        assert store.company.pk

    @given(lists(from_model(Company)))
    def test_can_get_multiple_models_with_unique_field(self, companies):
        assume(len(companies) > 1)
        for c in companies:
            self.assertIsNotNone(c.pk)
        self.assertEqual(
            len({c.pk for c in companies}), len({c.name for c in companies})
        )

    @settings(suppress_health_check=[HealthCheck.too_slow])
    @given(from_model(Customer))
    def test_is_customer(self, customer):
        self.assertIsInstance(customer, Customer)
        self.assertIsNotNone(customer.pk)
        self.assertIsNotNone(customer.email)

    @settings(suppress_health_check=[HealthCheck.too_slow])
    @given(from_model(Customer))
    def test_tz_presence(self, customer):
        if django_settings.USE_TZ:
            self.assertIsNotNone(customer.birthday.tzinfo)
        else:
            self.assertIsNone(customer.birthday.tzinfo)

    @given(from_model(CouldBeCharming))
    def test_is_not_charming(self, not_charming):
        self.assertIsInstance(not_charming, CouldBeCharming)
        self.assertIsNotNone(not_charming.pk)
        self.assertIsNone(not_charming.charm)

    @given(from_model(SelfLoop))
    def test_sl(self, sl):
        self.assertIsNone(sl.me)

    @given(lists(from_model(ManyNumerics)))
    def test_no_overflow_in_integer(self, manyints):
        pass

    @given(from_model(Customish))
    def test_custom_field(self, x):
        assert x.customish == "a"

    def test_mandatory_fields_are_mandatory(self):
        self.assertRaises(InvalidArgument, from_model(Store).example)

    def test_mandatory_computed_fields_are_mandatory(self):
        with self.assertRaises(InvalidArgument):
            from_model(MandatoryComputed).example()

    def test_mandatory_computed_fields_may_not_be_provided(self):
        mc = from_model(MandatoryComputed, company=from_model(Company))
        self.assertRaises(RuntimeError, mc.example)

    @given(from_model(CustomishDefault, customish=infer))
    def test_customish_default_overridden_by_infer(self, x):
        assert x.customish == "a"

    @given(from_model(CustomishDefault, customish=infer))
    def test_customish_infer_uses_registered_instead_of_default(self, x):
        assert x.customish == "a"

    @given(from_model(OddFields))
    def test_odd_fields(self, x):
        assert isinstance(x.uuid, UUID)
        assert isinstance(x.slug, str)
        assert " " not in x.slug
        assert isinstance(x.ipv4, str)
        assert len(x.ipv4.split(".")) == 4
        assert all(int(i) in range(256) for i in x.ipv4.split("."))
        assert isinstance(x.ipv6, str)
        assert set(x.ipv6).issubset(set("0123456789abcdefABCDEF:."))

    @given(from_model(ManyTimes))
    def test_time_fields(self, x):
        assert isinstance(x.time, dt.time)
        assert isinstance(x.date, dt.date)
        assert isinstance(x.duration, dt.timedelta)

    @given(from_model(Company))
    def test_no_null_in_charfield(self, x):
        # regression test for #1045.  Company just has a convenient CharField.
        assert "\x00" not in x.name

    @given(binary(min_size=10))
    def test_foreign_key_primary(self, buf):
        # Regression test for #1307
        company_strategy = from_model(Company, name=just("test"))
        strategy = from_model(
            CompanyExtension, company=company_strategy, self_modifying=just(2)
        )
        try:
            ConjectureData.for_buffer(buf).draw(strategy)
        except HypothesisException:
            reject()
        # Draw again with the same buffer. This will cause a duplicate
        # primary key.
        ConjectureData.for_buffer(buf).draw(strategy)
        assert CompanyExtension.objects.all().count() == 1
示例#39
0
import pytest

from hypothesis import given, settings
from hypothesis.database import (
    DirectoryBasedExampleDatabase,
    ExampleDatabase,
    InMemoryExampleDatabase,
    MultiplexedDatabase,
    ReadOnlyDatabase,
)
from hypothesis.strategies import binary, lists, tuples

small_settings = settings(max_examples=50)


@given(lists(tuples(binary(), binary())))
@small_settings
def test_backend_returns_what_you_put_in(xs):
    backend = InMemoryExampleDatabase()
    mapping = {}
    for key, value in xs:
        mapping.setdefault(key, set()).add(value)
        backend.save(key, value)
    for key, values in mapping.items():
        backend_contents = list(backend.fetch(key))
        distinct_backend_contents = set(backend_contents)
        assert len(backend_contents) == len(distinct_backend_contents)
        assert distinct_backend_contents == set(values)


def test_can_delete_keys():
示例#40
0
class HypothesisSpec(RuleBasedStateMachine):
    def __init__(self):
        super(HypothesisSpec, self).__init__()
        self.database = None

    strategies = Bundle(u'strategy')
    strategy_tuples = Bundle(u'tuples')
    objects = Bundle(u'objects')
    streaming_strategies = Bundle(u'streams')
    basic_data = Bundle(u'basic')
    varied_floats = Bundle(u'varied_floats')

    strats_with_parameters = Bundle(u'strats_with_parameters')
    strats_with_templates = Bundle(u'strats_with_templates')
    strats_with_2_templates = Bundle(u'strats_with_2_templates')

    def teardown(self):
        self.clear_database()

    @timeout(60, catchable=True)
    def execute_step(self, step):
        return super(HypothesisSpec, self).execute_step(step)

    @rule(target=basic_data, st=strats_with_templates)
    def to_basic(self, st):
        return st[0].to_basic(st[1])

    @rule(data=basic_data, strat=strategies)
    def from_basic(self, data, strat):
        try:
            template = strat.from_basic(data)
        except BadData:
            return
        strat.reify(template)

    @rule(target=basic_data, data=basic_data, r=randoms())
    def mess_with_basic(self, data, r):
        return mutate_basic(data, r)

    @rule()
    def clear_database(self):
        if self.database is not None:
            self.database.close()
            self.database = None

    @rule()
    def set_database(self):
        self.teardown()
        self.database = ExampleDatabase()

    @rule(st=strats_with_templates)
    def reify(self, st):
        strat, temp = st
        strat.reify(temp)

    @rule(target=strats_with_templates, st=strats_with_templates)
    def via_basic(self, st):
        strat, temp = st
        temp = strat.from_basic(strat.to_basic(temp))
        return (strat, temp)

    @rule(targets=(strategies, streaming_strategies), strat=strategies)
    def build_stream(self, strat):
        return streaming(strat)

    @rule(targets=(strategies, streaming_strategies),
          strat=strategies,
          i=integers(1, 10))
    def evalled_stream(self, strat, i):
        return streaming(strat).map(lambda x: list(x[:i]) and x)

    @rule(stream_strat=streaming_strategies, index=integers(0, 50))
    def eval_stream(self, stream_strat, index):
        try:
            stream = stream_strat.example()
            list(stream[:index])
        except NoExamples:
            pass

    @rule(target=strats_with_templates, st=strats_with_templates, r=randoms())
    def simplify(self, st, r):
        strat, temp = st
        for temp in strat.full_simplify(r, temp):
            break
        return (strat, temp)

    @rule(strat=strategies, r=randoms(), mshr=integers(0, 100))
    def find_constant_failure(self, strat, r, mshr):
        with Settings(
                verbosity=Verbosity.quiet,
                max_examples=1,
                min_satisfying_examples=0,
                database=self.database,
                max_shrinks=mshr,
        ):

            @given(
                strat,
                random=r,
            )
            def test(x):
                assert False

            try:
                test()
            except AssertionError:
                pass

    @rule(strat=strategies,
          r=randoms(),
          p=floats(0, 1),
          mex=integers(1, 10),
          mshr=integers(1, 100))
    def find_weird_failure(self, strat, r, mex, p, mshr):
        with Settings(
                verbosity=Verbosity.quiet,
                max_examples=mex,
                min_satisfying_examples=0,
                database=self.database,
                max_shrinks=mshr,
        ):

            @given(
                strat,
                random=r,
            )
            def test(x):
                assert Random(hashlib.md5(
                    show(x).encode(u'utf-8')).digest()).random() <= p

            try:
                test()
            except AssertionError:
                pass

    @rule(target=strats_with_parameters, strat=strategies, r=randoms())
    def draw_parameter(self, strat, r):
        return (strat, strat.draw_parameter(r))

    @rule(target=strats_with_templates, sp=strats_with_parameters, r=randoms())
    def draw_template(self, sp, r):
        strat, param = sp
        return (strat, strat.draw_template(r, param))

    @rule(target=strats_with_2_templates,
          sp=strats_with_parameters,
          r=randoms())
    def draw_templates(self, sp, r):
        strat, param = sp
        return (
            strat,
            strat.draw_template(r, param),
            strat.draw_template(r, param),
        )

    @rule(st=strats_with_templates)
    def check_serialization(self, st):
        strat, template = st
        as_basic = strat.to_basic(template)
        assert show(strat.reify(template)) == show(
            strat.reify(strat.from_basic(as_basic)))
        assert as_basic == strat.to_basic(strat.from_basic(as_basic))

    @rule(target=strategies,
          spec=sampled_from((
              integers(),
              booleans(),
              floats(),
              complex_numbers(),
              fractions(),
              decimals(),
              text(),
              binary(),
              none(),
              StateMachineSearchStrategy(),
              tuples(),
          )))
    def strategy(self, spec):
        return spec

    @rule(target=strategies, values=lists(integers() | text(), min_size=1))
    def sampled_from_strategy(self, values):
        return sampled_from(values)

    @rule(target=strategies, spec=strategy_tuples)
    def strategy_for_tupes(self, spec):
        return tuples(*spec)

    @rule(target=strategies,
          source=strategies,
          level=integers(1, 10),
          mixer=text())
    def filtered_strategy(s, source, level, mixer):
        def is_good(x):
            return bool(
                Random(
                    hashlib.md5(
                        (mixer + show(x)).encode(u'utf-8')).digest()).randint(
                            0, level))

        return source.filter(is_good)

    @rule(target=strategies, elements=strategies)
    def list_strategy(self, elements):
        return lists(elements, average_size=AVERAGE_LIST_LENGTH)

    @rule(target=strategies, l=strategies, r=strategies)
    def or_strategy(self, l, r):
        return l | r

    @rule(target=strategies,
          source=strategies,
          result=strategies,
          mixer=text())
    def mapped_strategy(self, source, result, mixer):
        cache = {}

        def do_map(value):
            rep = show(value)
            try:
                return deepcopy(cache[rep])
            except KeyError:
                pass
            random = Random(
                hashlib.md5((mixer + rep).encode(u'utf-8')).digest())
            outcome_template = result.draw_and_produce(random)
            cache[rep] = result.reify(outcome_template)
            return deepcopy(cache[rep])

        return source.map(do_map)

    @rule(target=varied_floats, source=floats())
    def float(self, source):
        return source

    @rule(target=varied_floats,
          source=varied_floats,
          offset=integers(-100, 100))
    def adjust_float(self, source, offset):
        return int_to_float(clamp(0, float_to_int(source) + offset, 2**64 - 1))

    @rule(target=strategies, left=varied_floats, right=varied_floats)
    def float_range(self, left, right):
        for f in (math.isnan, math.isinf):
            for x in (left, right):
                assume(not f(x))
        left, right = sorted((left, right))
        assert left <= right
        return floats(left, right)

    @rule(target=strategies,
          source=strategies,
          result1=strategies,
          result2=strategies,
          mixer=text(),
          p=floats(0, 1))
    def flatmapped_strategy(self, source, result1, result2, mixer, p):
        assume(result1 is not result2)

        def do_map(value):
            rep = show(value)
            random = Random(
                hashlib.md5((mixer + rep).encode(u'utf-8')).digest())
            if random.random() <= p:
                return result1
            else:
                return result2

        return source.flatmap(do_map)

    @rule(target=strategies, value=objects)
    def just_strategy(self, value):
        return just(value)

    @rule(target=strategy_tuples, source=strategies)
    def single_tuple(self, source):
        return (source, )

    @rule(target=strategy_tuples, l=strategy_tuples, r=strategy_tuples)
    def cat_tuples(self, l, r):
        return l + r

    @rule(target=objects, strat=strategies)
    def get_example(self, strat):
        try:
            strat.example()
        except NoExamples:
            # Because of filtering some strategies we look for don't actually
            # have any examples.
            pass

    @rule(target=strategies, left=integers(), right=integers())
    def integer_range(self, left, right):
        left, right = sorted((left, right))
        return integers(left, right)

    @rule(strat=strategies)
    def repr_is_good(self, strat):
        assert u' at 0x' not in repr(strat)

    @rule(strat=strategies)
    def template_upper_bound_is_valid(self, strat):
        ub = strat.template_upper_bound
        assert ub >= 0
        if isinstance(ub, float):
            assert math.isinf(ub)
        else:
            assert isinstance(ub, int)

    @rule(strat=strategies, r=randoms())
    def can_find_as_many_templates_as_size(self, strat, r):
        tempstrat = templates_for(strat)
        n = min(10, strat.template_upper_bound)
        found = []
        with Settings(verbosity=Verbosity.quiet, timeout=2.0):
            for i in range(n):
                try:
                    x = find(
                        tempstrat,
                        lambda t: t not in found,
                        random=r,
                    )
                except:
                    print(u'Exception at %d/%d. template_upper_bound=%r' %
                          (i, n, strat.template_upper_bound))
                    raise
                found.append(x)
示例#41
0
        num_func) == ((('/', ), ('Folder', )), (('/', ), ('Folder (', 1, ')')))


# The remaining tests provide no examples, just hypothesis tests.
# They only confirm that _natsort_key uses the above building blocks.


@given(floats() | integers())
def test__natsort_key_with_numeric_input_takes_number_path(x):
    assume(not isnan(x))
    assert _natsort_key(x, None, string_func, bytes_func,
                        num_func) == num_func(x)


@pytest.mark.skipif(PY_VERSION < 3, reason='only valid on python3')
@given(binary())
def test__natsort_key_with_bytes_input_takes_bytes_path(x):
    assume(x)
    assert _natsort_key(x, None, string_func, bytes_func,
                        num_func) == bytes_func(x)


@given(lists(elements=floats() | text() | integers(), min_size=1, max_size=10))
def test__natsort_key_with_text_input_takes_string_path(x):
    assume(not any(type(y) == float and isnan(y) for y in x))
    s = ''.join(repr(y) if type(y) in (float, long, int) else y for y in x)
    assert _natsort_key(s, None, string_func, bytes_func,
                        num_func) == string_func(s)


@given(lists(elements=text(), min_size=1, max_size=10))
示例#42
0
def binary_values(draw, kindstr):
    if kindstr == "char":
        return draw(binary_string())
    else:
        num_bytes = tokenlen(kindstr)
        return draw(st.binary(min_size=num_bytes, max_size=num_bytes))
def array_values(draw):
    matching = draw(st.lists(elements=st.binary(min_size=2, max_size=2)))
    non_matching = draw(
        st.lists(elements=st.binary(min_size=2, max_size=2)).filter(lambda x: x != matching))
    return (matching, non_matching)
示例#44
0
class TestRTP(TestCase):
    def setUp(self):
        self.thisRTP = RTP()

    def setup_example(self):
        self.setUp()

    @given(st.booleans(), st.booleans(), st.sampled_from(PayloadType),
           st.integers(min_value=0, max_value=(2**16) - 1),
           st.integers(min_value=0, max_value=(2**32) - 1),
           st.integers(min_value=0, max_value=(2**32) - 1),
           st.lists(st.integers(min_value=0, max_value=(2**16) - 1),
                    max_size=15), st.binary())
    def test_init(self, padding, marker, payloadType, sequenceNumber,
                  timestamp, ssrc, csrcList, payload):
        newExt = Extension()
        newRTP = RTP(version=2,
                     padding=padding,
                     marker=marker,
                     payloadType=payloadType,
                     sequenceNumber=sequenceNumber,
                     timestamp=timestamp,
                     ssrc=ssrc,
                     extension=newExt,
                     csrcList=csrcList,
                     payload=bytearray(payload))

        self.assertEqual(newRTP.version, 2)
        self.assertEqual(newRTP.padding, padding)
        self.assertEqual(newRTP.marker, marker)
        self.assertEqual(newRTP.payloadType, payloadType)
        self.assertEqual(newRTP.sequenceNumber, sequenceNumber)
        self.assertEqual(newRTP.timestamp, timestamp)
        self.assertEqual(newRTP.ssrc, ssrc)
        self.assertEqual(newRTP.extension, newExt)
        self.assertEqual(newRTP.csrcList, csrcList)
        self.assertEqual(newRTP.payload, payload)

    def test_version_default(self):
        # Test default
        self.assertEqual(self.thisRTP.version, 2)

    @given(st.integers())
    @example(2)
    def test_version(self, value):
        if value == 2:
            self.thisRTP.version = value
            self.assertEqual(self.thisRTP.version, value)
        else:
            with self.assertRaises(ValueError):
                self.thisRTP.version = value

    def test_padding_default(self):
        self.assertEqual(self.thisRTP.padding, False)

    @given(st.booleans())
    def test_padding(self, value):
        self.thisRTP.padding = value
        self.assertEqual(self.thisRTP.padding, value)

    def test_padding_invalidType(self):
        with self.assertRaises(AttributeError):
            self.thisRTP.padding = ""

    def test_marker_default(self):
        self.assertEqual(self.thisRTP.marker, False)

    @given(st.booleans())
    def test_marker(self, value):
        self.thisRTP.marker = value
        self.assertEqual(self.thisRTP.marker, value)

    def test_marker_invalidType(self):
        with self.assertRaises(AttributeError):
            self.thisRTP.marker = ""

    def test_payloadType_default(self):
        self.assertEqual(self.thisRTP.payloadType, PayloadType.DYNAMIC_96)

    @given(st.sampled_from(PayloadType))
    def test_payloadType(self, value):
        self.thisRTP.payloadType = value
        self.assertEqual(self.thisRTP.payloadType, value)

    def test_payloadType_invalidType(self):
        with self.assertRaises(AttributeError):
            self.thisRTP.payloadType = ""

    def test_sequenceNumber_default(self):
        self.assertIsInstance(self.thisRTP.sequenceNumber, int)

    @given(st.integers(min_value=0, max_value=(2**16) - 1))
    def test_sequenceNumber_valid(self, value):
        self.thisRTP.sequenceNumber = value
        self.assertEqual(self.thisRTP.sequenceNumber, value)

    @given(st.integers().filter(lambda x: (x < 0) or (x >= 2**16)))
    def test_sequenceNumber_invalid(self, value):
        with self.assertRaises(ValueError):
            self.thisRTP.sequenceNumber = value

    def test_sequenceNumber_invalidType(self):
        with self.assertRaises(AttributeError):
            self.thisRTP.sequenceNumber = ""

    def test_timestamp_default(self):
        self.assertEqual(self.thisRTP.timestamp, 0)

    @given(st.integers(min_value=0, max_value=(2**32) - 1))
    def test_timestamp_valid(self, value):
        self.thisRTP.timestamp = value
        self.assertEqual(self.thisRTP.timestamp, value)

    @given(st.integers().filter(lambda x: (x < 0) or (x >= 2**32)))
    def test_timestamp_invalid(self, value):
        with self.assertRaises(ValueError):
            self.thisRTP.timestamp = value

    def test_timestamp_invalidType(self):
        with self.assertRaises(AttributeError):
            self.thisRTP.timestamp = ""

    def test_ssrc_default(self):
        self.assertIsInstance(self.thisRTP.ssrc, int)

    @given(st.integers(min_value=0, max_value=(2**32) - 1))
    def test_ssrc_valid(self, value):
        self.thisRTP.ssrc = value
        self.assertEqual(self.thisRTP.ssrc, value)

    @given(st.integers().filter(lambda x: (x < 0) or (x >= 2**32)))
    def test_ssrc_invalid(self, value):
        with self.assertRaises(ValueError):
            self.thisRTP.ssrc = value

    def test_ssrc_invalidType(self):
        with self.assertRaises(AttributeError):
            self.thisRTP.ssrc = ""

    def test_extension_default(self):
        self.assertEqual(self.thisRTP.extension, None)

    def test_extension(self):
        self.thisRTP.extension = None
        self.assertEqual(self.thisRTP.extension, None)

        newExt = Extension()
        self.thisRTP.extension = newExt
        self.assertEqual(self.thisRTP.extension, newExt)

    def test_extension_invalidType(self):
        with self.assertRaises(AttributeError):
            self.thisRTP.extension = ""

    def test_csrcList_default(self):
        self.assertEqual(self.thisRTP.csrcList, CSRCList())

    def test_payload_default(self):
        self.assertEqual(self.thisRTP.payload, bytearray())

    @given(st.binary())
    def test_payload(self, value):
        self.thisRTP.payload = bytearray(value)
        self.assertEqual(self.thisRTP.payload, value)

    def test_payload_invalidType(self):
        with self.assertRaises(AttributeError):
            self.thisRTP.payload = ""

    def test_fromBytearray_default(self):
        self.thisRTP.sequenceNumber = 0
        self.thisRTP.ssrc = 0
        default = bytearray(
            b'\x80\x60\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')

        newRTP = RTP().fromBytearray(default)
        self.assertEqual(newRTP, self.thisRTP)

    def test_toBytearray_default(self):
        self.thisRTP.sequenceNumber = 0
        self.thisRTP.ssrc = 0
        expected = b'\x80\x60\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
        self.assertEqual(self.thisRTP.toBytearray(), expected)

    @given(st.booleans())
    def test_fromBytearray_padding(self, value):
        self.thisRTP.sequenceNumber = 0
        self.thisRTP.ssrc = 0
        payload = bytearray(
            b'\x80\x60\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')
        payload[0] |= value << 5
        newRTP = RTP().fromBytearray(payload)

        self.thisRTP.padding = value
        self.assertEqual(newRTP, self.thisRTP)

    @given(st.booleans())
    def test_toBytearray_padding(self, value):
        self.thisRTP.sequenceNumber = 0
        self.thisRTP.ssrc = 0
        expected = bytearray(
            b'\x80\x60\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')
        expected[0] |= value << 5
        self.thisRTP.padding = value
        self.assertEqual(self.thisRTP.toBytearray(), expected)

    @given(st.binary(min_size=2, max_size=2),
           st.binary(max_size=((2**16) - 1) *
                     4).filter(lambda x: (len(x) % 4) == 0))
    def test_fromBytearray_extension(self, startBits, headerExtension):
        self.thisRTP.sequenceNumber = 0
        self.thisRTP.ssrc = 0
        newExt = Extension()
        newExt.startBits = bytearray(startBits)
        newExt.headerExtension = bytearray(headerExtension)

        payload = bytearray(
            b'\x80\x60\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')
        payload[0] |= 1 << 4
        payload[12:12] = newExt.toBytearray()
        newRTP = RTP().fromBytearray(payload)

        self.thisRTP.extension = newExt
        self.assertEqual(newRTP, self.thisRTP)

    @given(st.binary(min_size=2, max_size=2),
           st.binary(max_size=((2**16) - 1) *
                     4).filter(lambda x: (len(x) % 4) == 0))
    def test_toBytearray_extension(self, startBits, headerExtension):
        self.thisRTP.sequenceNumber = 0
        self.thisRTP.ssrc = 0
        newExt = Extension()
        newExt.startBits = bytearray(startBits)
        newExt.headerExtension = bytearray(headerExtension)

        expected = bytearray(
            b'\x80\x60\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')
        expected[0] |= 1 << 4
        expected[12:12] = newExt.toBytearray()
        self.thisRTP.extension = newExt
        self.assertEqual(self.thisRTP.toBytearray(), expected)

    @given(
        st.lists(st.integers(min_value=0, max_value=(2**16) - 1), max_size=15))
    def test_fromBytearray_csrcList(self, value):
        self.thisRTP.sequenceNumber = 0
        self.thisRTP.ssrc = 0
        payload = bytearray(
            b'\x80\x60\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')
        payload[0] |= len(value)
        for x in range(len(value)):
            payload[12 + (4 * x):12 + (4 * x)] = value[x].to_bytes(
                4, byteorder='big')
        newRTP = RTP().fromBytearray(payload)

        self.thisRTP.csrcList.extend(value)
        self.assertEqual(newRTP, self.thisRTP)

    @given(
        st.lists(st.integers(min_value=0, max_value=(2**16) - 1), max_size=15))
    def test_toBytearray_csrcList(self, value):
        self.thisRTP.sequenceNumber = 0
        self.thisRTP.ssrc = 0
        expected = bytearray(
            b'\x80\x60\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')
        expected[0] |= len(value)
        for x in range(len(value)):
            expected[12 + (4 * x):12 + (4 * x)] = value[x].to_bytes(
                4, byteorder='big')

        self.thisRTP.csrcList.extend(value)
        self.assertEqual(self.thisRTP.toBytearray(), expected)

    @given(st.booleans())
    def test_fromBytearray_marker(self, value):
        self.thisRTP.sequenceNumber = 0
        self.thisRTP.ssrc = 0
        payload = bytearray(
            b'\x80\x60\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')
        payload[1] |= value << 7
        newRTP = RTP().fromBytearray(payload)

        self.thisRTP.marker = value
        self.assertEqual(newRTP, self.thisRTP)

    @given(st.booleans())
    def test_toBytearray_marker(self, value):
        self.thisRTP.sequenceNumber = 0
        self.thisRTP.ssrc = 0
        expected = bytearray(
            b'\x80\x60\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')
        expected[1] |= value << 7

        self.thisRTP.marker = value
        self.assertEqual(self.thisRTP.toBytearray(), expected)

    @given(st.sampled_from(PayloadType))
    def test_fromBytearray_payloadType(self, value):
        self.thisRTP.sequenceNumber = 0
        self.thisRTP.ssrc = 0
        payload = bytearray(
            b'\x80\x60\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')
        payload[1] = value.value
        newRTP = RTP().fromBytearray(payload)

        self.thisRTP.payloadType = value
        self.assertEqual(newRTP, self.thisRTP)

    @given(st.sampled_from(PayloadType))
    def test_toBytearray_payloadType(self, value):
        self.thisRTP.sequenceNumber = 0
        self.thisRTP.ssrc = 0
        expected = bytearray(
            b'\x80\x60\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')
        expected[1] = value.value

        self.thisRTP.payloadType = value
        self.assertEqual(self.thisRTP.toBytearray(), expected)

    @given(st.integers(min_value=0, max_value=(2**16) - 1))
    def test_fromBytearray_sequenceNumber(self, value):
        self.thisRTP.sequenceNumber = 0
        self.thisRTP.ssrc = 0
        payload = bytearray(
            b'\x80\x60\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')
        payload[2:4] = value.to_bytes(2, byteorder='big')
        newRTP = RTP().fromBytearray(payload)

        self.thisRTP.sequenceNumber = value
        self.assertEqual(newRTP, self.thisRTP)

    @given(st.integers(min_value=0, max_value=(2**16) - 1))
    def test_toBytearray_sequenceNumber(self, value):
        self.thisRTP.sequenceNumber = 0
        self.thisRTP.ssrc = 0
        expected = bytearray(
            b'\x80\x60\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')
        expected[2:4] = value.to_bytes(2, byteorder='big')
        self.thisRTP.sequenceNumber = value
        self.assertEqual(self.thisRTP.toBytearray(), expected)

    @given(st.integers(min_value=0, max_value=(2**32) - 1))
    def test_fromBytearray_timestamp(self, value):
        self.thisRTP.sequenceNumber = 0
        self.thisRTP.ssrc = 0
        payload = bytearray(
            b'\x80\x60\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')
        payload[4:8] = value.to_bytes(4, byteorder='big')
        newRTP = RTP().fromBytearray(payload)

        self.thisRTP.timestamp = value
        self.assertEqual(newRTP, self.thisRTP)

    @given(st.integers(min_value=0, max_value=(2**32) - 1))
    def test_toBytearray_timestamp(self, value):
        self.thisRTP.sequenceNumber = 0
        self.thisRTP.ssrc = 0
        expected = bytearray(
            b'\x80\x60\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')
        expected[4:8] = value.to_bytes(4, byteorder='big')
        self.thisRTP.timestamp = value
        self.assertEqual(self.thisRTP.toBytearray(), expected)

    @given(st.integers(min_value=0, max_value=(2**32) - 1))
    def test_fromBytearray_ssrc(self, value):
        self.thisRTP.sequenceNumber = 0
        self.thisRTP.ssrc = 0
        payload = bytearray(
            b'\x80\x60\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')
        payload[8:12] = value.to_bytes(4, byteorder='big')
        newRTP = RTP().fromBytearray(payload)

        self.thisRTP.ssrc = value
        self.assertEqual(newRTP, self.thisRTP)

    @given(st.integers(min_value=0, max_value=(2**32) - 1))
    def test_toBytearray_ssrc(self, value):
        self.thisRTP.sequenceNumber = 0
        self.thisRTP.ssrc = 0
        expected = bytearray(
            b'\x80\x60\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')
        expected[8:12] = value.to_bytes(4, byteorder='big')
        self.thisRTP.ssrc = value
        self.assertEqual(self.thisRTP.toBytearray(), expected)

    @given(st.binary())
    def test_fromBytearray_payload(self, value):
        self.thisRTP.sequenceNumber = 0
        self.thisRTP.ssrc = 0
        payload = bytearray(
            b'\x80\x60\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')
        payload += value
        newRTP = RTP().fromBytearray(payload)

        self.thisRTP.payload = bytearray(value)
        self.assertEqual(newRTP, self.thisRTP)

    @given(st.binary())
    def test_toBytearray_payload(self, value):
        self.thisRTP.sequenceNumber = 0
        self.thisRTP.ssrc = 0
        expected = bytearray(
            b'\x80\x60\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')
        expected += value
        self.thisRTP.payload = bytearray(value)
        self.assertEqual(self.thisRTP.toBytearray(), expected)

    def test_fromBytes_default(self):
        self.thisRTP.sequenceNumber = 0
        self.thisRTP.ssrc = 0
        default = b'\x80\x60\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'

        newRTP = RTP().fromBytes(default)
        self.assertEqual(newRTP, self.thisRTP)

    def test_toBytes_default(self):
        self.thisRTP.sequenceNumber = 0
        self.thisRTP.ssrc = 0
        expected = b'\x80\x60\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
        self.assertEqual(self.thisRTP.toBytes(), expected)

    def test_bytes_default(self):
        self.thisRTP.sequenceNumber = 0
        self.thisRTP.ssrc = 0
        expected = b'\x80\x60\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
        self.assertEqual(bytes(self.thisRTP), expected)
示例#45
0
def states_inputs_outputs(draw):
    length = draw(st.integers(min_value=1, max_value=100))
    allowed = st.sets(st.one_of(st.integers(), st.characters()),
                      min_size=length,
                      max_size=length)
    states = list(draw(allowed))
    inputs = list(draw(allowed))
    outputs = list(draw(allowed))
    return states, inputs, outputs


@given(
    data=states_inputs_outputs(),
    seed=st.one_of(
        st.integers().filter(lambda val: val != 0),
        st.binary(min_size=1),
        st.floats().filter(lambda val: val != 0.0),
        st.text(min_size=1),
    ),
)
def test_generate_equal(data, seed):
    states, inputs, outputs = data
    fsm1 = generate(states, inputs, outputs, seed)
    fsm2 = generate(states, inputs, outputs, seed)
    assert fsm1.transition == fsm2.transition
    assert fsm1.emit == fsm2.emit


class GeneratedFiniteStateMachine(RuleBasedStateMachine):
    """
    Testing correctness of finite state machine.

def test_chaindb_persist_header(chaindb, header):
    with pytest.raises(HeaderNotFound):
        chaindb.get_block_header_by_hash(header.hash)
    number_to_hash_key = SchemaV1.make_block_hash_to_score_lookup_key(
        header.hash)
    assert not chaindb.exists(number_to_hash_key)

    chaindb.persist_header(header)

    assert chaindb.get_block_header_by_hash(header.hash) == header
    assert chaindb.exists(number_to_hash_key)


@given(seed=st.binary(min_size=32, max_size=32))
def test_chaindb_persist_header_unknown_parent(chaindb, header, seed):
    n_header = header.copy(parent_hash=keccak(seed))
    with pytest.raises(ParentNotFound):
        chaindb.persist_header(n_header)


def test_chaindb_persist_block(chaindb, block):
    block = block.copy(header=set_empty_root(chaindb, block.header))
    block_to_hash_key = SchemaV1.make_block_hash_to_score_lookup_key(
        block.hash)
    assert not chaindb.exists(block_to_hash_key)
    chaindb.persist_block(block)
    assert chaindb.exists(block_to_hash_key)

示例#47
0
import pytest

from hypothesis import given, strategies as st
from hypothesis.errors import Frozen
from hypothesis.internal.compat import hbytes, hrange
from hypothesis.internal.conjecture.data import (
    ConjectureData,
    DataObserver,
    Status,
    StopTest,
)
from hypothesis.searchstrategy.strategies import SearchStrategy


@given(st.binary())
def test_buffer_draws_as_self(buf):
    x = ConjectureData.for_buffer(buf)
    assert x.draw_bytes(len(buf)) == buf


def test_cannot_draw_after_freeze():
    x = ConjectureData.for_buffer(b"hi")
    x.draw_bytes(1)
    x.freeze()
    with pytest.raises(Frozen):
        x.draw_bytes(1)


def test_can_double_freeze():
    x = ConjectureData.for_buffer(b"hi")
示例#48
0

@pt.mark.parametrize('seq,length,payload,body', example_datagrams)
def test_datagram_parse(seq: int, length: int, payload: bytes,
                        body: bytes) -> None:
    """Test Datagram parsing from body."""
    datagram = datagrams.Datagram()
    datagram.parse(body)
    assert datagram.seq == seq
    assert datagram.length == length
    assert datagram.payload == payload


@hp.given(seq=st.integers(min_value=0, max_value=255),
          length=st.integers(min_value=0, max_value=255),
          payload=st.binary(max_size=255))
@hp.example(seq=0, length=0, payload=b'')
@hp.example(seq=255, length=255, payload=bytes(list(range(255))))
def test_datagram_parse_invariants(seq: int, length: int,
                                   payload: bytes) -> None:
    """Test Datagram parse invariants."""
    datagram = datagrams.Datagram()
    datagram.parse(bytes([seq, length]) + payload)
    assert datagram.seq == seq
    assert datagram.length == length
    assert datagram.payload == payload


@hp.given(body=st.binary(max_size=1))
def test_datagram_parse_invalid(body: bytes) -> None:
    """Test Datagram parse errors."""
    return False


def all_bytes_equal(test_bytes, target):
    if sys.version_info.major < 3:
        return all(byte == chr(target) for byte in test_bytes)
    else:
        return all(byte == target for byte in test_bytes)


@settings(max_examples=250)
@given(
    integer_bit_size=st.integers(min_value=1,
                                 max_value=32).map(lambda v: v * 8),
    stream_bytes=st.binary(min_size=0, max_size=32),
    data_byte_size=st.integers(min_value=0, max_value=32),
)
def test_decode_unsigned_int(integer_bit_size, stream_bytes, data_byte_size):
    if integer_bit_size % 8 != 0:
        with pytest.raises(ValueError):
            UnsignedIntegerDecoder(
                value_bit_size=integer_bit_size,
                data_byte_size=data_byte_size,
            )
        return
    elif integer_bit_size > data_byte_size * 8:
        with pytest.raises(ValueError):
            UnsignedIntegerDecoder(
                value_bit_size=integer_bit_size,
                data_byte_size=data_byte_size,
示例#50
0
compose = lambda f, g: lambda *x: f(g(*x))
# see https://docs.python.org/3/library/typing.html
try:
    unicode = unicode
except:
    unicode = str
    map = compose(list, map)
    from functools import reduce
primitives = {
    str: st.text(),  # might want to default to `string.printable`
    int: st.integers(),
    bool: st.booleans(),
    float: st.floats(),
    type(None): st.none(),
    unicode: st.characters(),
    bytes: st.binary()  # this is weird because str == bytes in py2
}  # missing: fractions, decimal


# it's not possible to make this typesafe, because
# we need `issinstance` to narrow down the types of types,
# and we are using `issubclass`
# there's also a FrozenSet type
# IO types ("file-like")
# re type
def type_to_strat(x, opts):  # type: (type) -> SearchStrategy
    '''
   Given a type, return a strategy which yields a value of that type. Types maybe complex: Union, NamedTuple, etc.
   For more information, see https://docs.python.org/3/library/typing.html
   Usage:
   >>> type_to_strat(Union[int,str]).exmample()
示例#51
0

@given(password_set=st.sets(st.sampled_from(string.ascii_letters),
                            min_size=10))
@settings(verbosity=Verbosity.verbose)
def test_long_letter_password(password_set):
    password = "".join(password_set)
    assert is_acceptable_password(password), "Long letter password"


@given(password_set=st.sets(st.sampled_from(string.ascii_letters +
                                            string.digits),
                            min_size=7,
                            max_size=9))
@settings(verbosity=Verbosity.verbose)
def test_acceptable_password(password_set):
    password = "".join(password_set)
    assert is_acceptable_password(password), "Acceptable password"


def test_no_args():
    with pytest.raises(TypeError):
        is_acceptable_password()


@given(invalid_arg=st.one_of(st.integers(), st.floats(), st.binary()))
@settings(verbosity=Verbosity.verbose)
def test_incorrect_args(invalid_arg):
    with pytest.raises(TypeError):
        is_acceptable_password(invalid_arg)
示例#52
0
class HTTPRequestWrappingIRequestTests(TestCase):
    """
    Tests for L{HTTPRequestWrappingIRequest}.
    """

    def legacyRequest(
        self,
        path=b"/",  # type: bytes
        method=b"GET",  # type: bytes
        host=b"localhost",  # type: bytes
        port=8080,  # type: int
        isSecure=False,  # type: bool
        body=None,  # type: Optional[bytes]
        headers=None,  # type: Optional[Headers]
    ):
        # type: (...) -> IRequest
        return requestMock(
            path=path,
            method=method,
            host=host,
            port=port,
            isSecure=isSecure,
            body=body,
            headers=headers,
        )

    def test_interface(self):
        # type: () -> None
        """
        L{HTTPRequestWrappingIRequest} implements L{IHTTPRequest}.
        """
        request = HTTPRequestWrappingIRequest(request=self.legacyRequest())
        self.assertProvides(IHTTPRequest, request)

    @given(text(alphabet=ascii_uppercase, min_size=1))
    def test_method(self, methodText):
        # type: (Text) -> None
        """
        L{HTTPRequestWrappingIRequest.method} matches the underlying legacy
        request method.
        """
        legacyRequest = self.legacyRequest(method=methodText.encode("ascii"))
        request = HTTPRequestWrappingIRequest(request=legacyRequest)
        self.assertEqual(request.method, methodText)

    @given(decoded_urls())
    def test_uri(self, url):
        # type: (DecodedURL) -> None
        """
        L{HTTPRequestWrappingIRequest.uri} matches the underlying legacy
        request URI.
        """
        uri = url.asURI()  # Normalize as (computer-friendly) URI

        assert uri.port is not None  # Tells mypy it's not an Optional

        path = (
            uri.replace(scheme="", host="", port=None).asText().encode("ascii")
        )
        legacyRequest = self.legacyRequest(
            isSecure=(uri.scheme == "https"),
            host=uri.host.encode("ascii"),
            port=uri.port,
            path=path,
        )
        request = HTTPRequestWrappingIRequest(request=legacyRequest)

        uriNormalized = uri
        requestURINormalized = request.uri.asURI()

        # Needed because non-equal URLs can render as the same strings
        def strURL(url):
            # type: (EncodedURL) -> Text
            return (
                "URL(scheme={url.scheme!r}, "
                "userinfo={url.userinfo!r}, "
                "host={url.host!r}, "
                "port={url.port!r}, "
                "path={url.path!r}, "
                "query={url.query!r}, "
                "fragment={url.fragment!r}, "
                "rooted={url.rooted})"
            ).format(url=url)

        self.assertEqual(
            requestURINormalized,
            uriNormalized,
            "{} != {}".format(
                strURL(requestURINormalized), strURL(uriNormalized)
            ),
        )

    def test_headers(self):
        # type: () -> None
        """
        L{HTTPRequestWrappingIRequest.headers} returns an
        L{HTTPRequestWrappingIRequest} containing the underlying legacy request
        headers.
        """
        legacyRequest = self.legacyRequest()
        request = HTTPRequestWrappingIRequest(request=legacyRequest)
        self.assertProvides(IHTTPHeaders, request.headers)

    def test_bodyAsFountTwice(self):
        # type: () -> None
        """
        L{HTTPRequestWrappingIRequest.bodyAsFount} raises
        L{FountAlreadyAccessedError} if called more than once.
        """
        legacyRequest = self.legacyRequest()
        request = HTTPRequestWrappingIRequest(request=legacyRequest)
        request.bodyAsFount()
        self.assertRaises(FountAlreadyAccessedError, request.bodyAsFount)

    @given(binary())
    def test_bodyAsBytes(self, data):
        # type: (bytes) -> None
        """
        L{HTTPRequestWrappingIRequest.bodyAsBytes} matches the underlying
        legacy request body.
        """
        legacyRequest = self.legacyRequest(body=data)
        request = HTTPRequestWrappingIRequest(request=legacyRequest)
        body = self.successResultOf(request.bodyAsBytes())

        self.assertEqual(body, data)

    def test_bodyAsBytesCached(self):
        # type: () -> None
        """
        L{HTTPRequestWrappingIRequest.bodyAsBytes} called twice returns the
        same object both times.
        """
        data = b"some data"
        legacyRequest = self.legacyRequest(body=data)
        request = HTTPRequestWrappingIRequest(request=legacyRequest)
        body1 = self.successResultOf(request.bodyAsBytes())
        body2 = self.successResultOf(request.bodyAsBytes())

        self.assertIdentical(body1, body2)
示例#53
0
S3_NAME_REGEX = r'[a-z0-9]([a-z0-9]|[-.]){1,61}[a-z0-9]'


def test_s3_service_builder():
    with patch.object(storage.boto3, 'resource', return_value='result'):
        # Relevant function call.
        s3 = storage._s3()
        # Assertions.
        storage.boto3.resource.assert_called_with(service_name='s3')
        assert s3 == 'result'


@given(
    obj_name=st.from_regex(S3_NAME_REGEX),
    text=st.one_of(st.text(), st.binary())
)
def test_write_string_to_object(obj_name: str, text: Union[str, bytes]):
    # Build some mocks.
    mock_s3_service = MagicMock(spec=['Bucket'])
    mock_bucket = MagicMock(spec=['put_object'])
    mock_s3_service.Bucket.return_value = mock_bucket
    # Patch them in.
    with patch.object(storage, '_s3', return_value=mock_s3_service):
        # Relevant function call.
        storage.write_string_to_object(object_name=obj_name, text=text)
        # Assertions.
        mock_s3_service.Bucket.assert_called_with(storage.conf['S3_BUCKET'])
        text_as_bytes = text.encode() if isinstance(text, str) else text
        mock_bucket.put_object.assert_called_with(Key=obj_name, Body=text_as_bytes)
    TestOneOfSameType = strategy_test_suite(
        one_of(
            integers(min_value=1, max_value=10),
            integers(min_value=8, max_value=15),
        ))
    TestRandom = strategy_test_suite(randoms())
    TestInts = strategy_test_suite(integers())
    TestBoolLists = strategy_test_suite(lists(booleans()))
    TestDictionaries = strategy_test_suite(
        dictionaries(keys=tuples(integers(), integers()), values=booleans()))
    TestOrderedDictionaries = strategy_test_suite(
        dictionaries(keys=integers(),
                     values=integers(),
                     dict_class=OrderedDict))
    TestString = strategy_test_suite(text())
    BinaryString = strategy_test_suite(binary())
    TestIntBool = strategy_test_suite(tuples(integers(), booleans()))
    TestFloats = strategy_test_suite(floats())
    TestComplex = strategy_test_suite(complex_numbers())
    TestJust = strategy_test_suite(just(u'hi'))
    TestTemplates = strategy_test_suite(templates_for(sets(integers())))

    TestEmptyString = strategy_test_suite(text(alphabet=u''))
    TestSingleString = strategy_test_suite(
        text(alphabet=u'a', average_size=10.0))
    TestManyString = strategy_test_suite(text(alphabet=u'abcdef☃'))

    Stuff = namedtuple(u'Stuff', (u'a', u'b'))
    TestNamedTuple = strategy_test_suite(builds(Stuff, integers(), integers()))

    TestTrees = strategy_test_suite(
示例#55
0
class TestCompressionCode(unittest.TestCase):
    """Property tests for Huffman functions"""
    @given(binary(0, 100, 1000))
    def test_make_freq_dict(self, byte_list):
        """make_freq_dict returns dictionary whose values
        sum to the number of bytes consumed"""

        b, d = byte_list, make_freq_dict(byte_list)
        self.assertTrue(isinstance(d, dict))
        self.assertEqual(sum(d.values()), len(b))

    @given(dictionaries(integers(0, 255), integers(1, 1000), dict, 2, 256,
                        256))
    def test_huffman_tree(self, d):
        """huffman_tree returns a non-leaf HuffmanNode"""

        t = huffman_tree(d)
        self.assertTrue(isinstance(t, HuffmanNode))
        self.assertTrue(not t.is_leaf())

    @given(dictionaries(integers(0, 255), integers(1, 1000), dict, 2, 256,
                        256))
    def test_get_codes(self, d):
        """the sum of len(code) * freq_dict[code] is optimal, so it
        must be invariant under permutation of the dictionary"""
        # NB: this also tests huffman_tree indirectly

        t = huffman_tree(d)
        c1 = get_codes(t)
        d2 = list(d.items())
        shuffle(d2)
        d2 = dict(d2)
        t2 = huffman_tree(d2)
        c2 = get_codes(t2)
        self.assertEqual(sum([d[k] * len(c1[k]) for k in d]),
                         sum([d2[k] * len(c2[k]) for k in d2]))

    @given(dictionaries(integers(0, 255), integers(1, 1000), dict, 2, 256,
                        256))
    def test_number_nodes(self, d):
        """if the root is an interior node, it must be numbered
        two less than the number of symbols"""
        # a complete tree has one fewer interior nodes than
        # it has leaves, and we are numbering from 0
        # NB: this also tests huffman_tree indirectly

        t = huffman_tree(d)
        assume(not t.is_leaf())
        count = len(d)
        number_nodes(t)
        self.assertEqual(count, t.number + 2)

    @given(dictionaries(integers(0, 255), integers(1, 1000), dict, 2, 256,
                        256))
    def test_avg_length(self, d):
        """avg_length should return a float in the
        interval [0, 8]"""

        t = huffman_tree(d)
        f = avg_length(t, d)
        self.assertTrue(isinstance(f, float))
        self.assertTrue(0 <= f <= 8.0)

    @given(binary(2, 100, 1000))
    def test_generate_compressed(self, b):
        """generate_compressed should return a bytes
        object that is no longer than the input bytes, and
        the size of the compressed object should be
        invariant under permuting the input"""
        # NB: this also indirectly tests make_freq_dict, huffman_tree,
        # and get_codes

        d = make_freq_dict(b)
        t = huffman_tree(d)
        c = get_codes(t)
        compressed = generate_compressed(b, c)
        self.assertTrue(isinstance(compressed, bytes))
        self.assertTrue(len(compressed) <= len(b))
        l = list(b)
        shuffle(l)
        b = bytes(l)
        d = make_freq_dict(b)
        t = huffman_tree(d)
        c = get_codes(t)
        compressed2 = generate_compressed(b, c)
        self.assertEqual(len(compressed2), len(compressed))

    @given(binary(2, 100, 1000))
    def test_tree_to_bytes(self, b):
        """tree_to_bytes generates a bytes representation of
        a post-order traversal of a trees internal nodes"""
        # Since each internal node requires 4 bytes to represent,
        # and there are 1 fewer internal node than distinct symbols,
        # the length of the bytes produced should be 4 times the
        # length of the frequency dictionary, minus 4"""
        # NB: also indirectly tests make_freq_dict, huffman_tree, and
        # number_nodes

        d = make_freq_dict(b)
        assume(len(d) > 1)
        t = huffman_tree(d)
        number_nodes(t)
        output_bytes = tree_to_bytes(t)
        dictionary_length = len(d)
        leaf_count = dictionary_length
        self.assertEqual(4 * (leaf_count - 1), len(output_bytes))

    @given(binary(2, 100, 1000))
    def test_num_nodes_to_bytes(self, b):
        """num_nodes_to_bytes returns a bytes object that
        has length 1 (since the number of internal nodes cannot
        exceed 256)"""
        # NB: also indirectly tests make_freq_dict and huffman_tree

        d = make_freq_dict(b)
        assume(len(d) > 1)
        t = huffman_tree(d)
        number_nodes(t)
        n = num_nodes_to_bytes(t)
        self.assertTrue(isinstance(n, bytes))
        self.assertEqual(len(n), 1)
示例#56
0
SCALAR_MAPPINGS = {
    FieldDescriptor.TYPE_DOUBLE: st.floats(),
    FieldDescriptor.TYPE_FLOAT: st.floats(**SINGLEPRECISION),
    FieldDescriptor.TYPE_INT32: st.integers(**RANGE32),
    FieldDescriptor.TYPE_INT64: st.integers(**RANGE64),
    FieldDescriptor.TYPE_UINT32: st.integers(**URANGE32),
    FieldDescriptor.TYPE_UINT64: st.integers(**URANGE64),
    FieldDescriptor.TYPE_SINT32: st.integers(**RANGE32),
    FieldDescriptor.TYPE_SINT64: st.integers(**RANGE64),
    FieldDescriptor.TYPE_FIXED32: st.integers(**URANGE32),
    FieldDescriptor.TYPE_FIXED64: st.integers(**URANGE64),
    FieldDescriptor.TYPE_SFIXED32: st.integers(**URANGE32),
    FieldDescriptor.TYPE_SFIXED64: st.integers(**URANGE64),
    FieldDescriptor.TYPE_BOOL: st.booleans(),
    FieldDescriptor.TYPE_STRING: st.text(),
    FieldDescriptor.TYPE_BYTES: st.binary()
}

LABEL_MAPPINGS = {
    FieldDescriptor.LABEL_OPTIONAL: partial(
        st.one_of, st.none()
    ),  # N.B. NoneType is not a valid proto value, but is handled in buildable
    FieldDescriptor.LABEL_REPEATED: st.lists,
    FieldDescriptor.LABEL_REQUIRED: lambda x: x
}


def overridable(f):
    """
    Handle overrides in a strategy-generating function, taking a field as a
    first argument.
示例#57
0
 bool:
 st.booleans(),
 int:
 st.integers(),
 float:
 st.floats(),
 complex:
 st.complex_numbers(),
 fractions.Fraction:
 st.fractions(),
 decimal.Decimal:
 st.decimals(),
 str:
 st.text(),
 bytes:
 st.binary(),
 datetime.datetime:
 st.datetimes(),
 datetime.date:
 st.dates(),
 datetime.time:
 st.times(),
 datetime.timedelta:
 st.timedeltas(),
 datetime.timezone:
 st.builds(datetime.timezone, offset=utc_offsets)
 | st.builds(datetime.timezone,
             offset=utc_offsets,
             name=st.text(st.characters())),
 uuid.UUID:
 st.uuids(),
示例#58
0
    'attachment; filename="{}"',
    'inline; {}',
    'attachment; {}="foo"',
    "attachment; filename*=iso-8859-1''{}",
    'attachment; filename*={}',
])
@hypothesis.given(strategies.text(alphabet=[chr(x) for x in range(255)]))
def test_parse_content_disposition_hypothesis(caplog, template, stubs, s):
    """Test parsing headers based on templates which hypothesis completes."""
    header = template.format(s)
    reply = stubs.FakeNetworkReply(headers={'Content-Disposition': header})
    with caplog.at_level(logging.ERROR, 'network'):
        http.parse_content_disposition(reply)


@hypothesis.given(strategies.binary())
def test_content_disposition_directly_hypothesis(s):
    """Test rfc6266 parsing directly with binary data."""
    try:
        cd = http.ContentDisposition.parse(s)
        cd.filename()
    except http.ContentDispositionError:
        pass


@pytest.mark.parametrize('content_type, expected_mimetype, expected_rest', [
    (None, None, None),
    ('image/example', 'image/example', None),
    ('', '', None),
    ('image/example; encoding=UTF-8', 'image/example', ' encoding=UTF-8'),
])
示例#59
0
# 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

import math

from hypothesis import given, strategies as st
from hypothesis.internal.compat import ceil, floor, int_from_bytes, int_to_bytes


@given(st.binary())
def test_convert_back(bs):
    bs = bytearray(bs)
    assert int_to_bytes(int_from_bytes(bs), len(bs)) == bs


bytes8 = st.builds(bytearray, st.binary(min_size=8, max_size=8))


@given(bytes8, bytes8)
def test_to_int_in_big_endian_order(x, y):
    x, y = sorted((x, y))
    assert 0 <= int_from_bytes(x) <= int_from_bytes(y)


ints8 = st.integers(min_value=0, max_value=2**63 - 1)
        ("bool", "string", TypeError),
        ("uint24", -20, TypeError),
    ]
)
def test_hex_encode_abi_type(abi_type, value, expected):

    if isinstance(expected, type) and issubclass(expected, Exception):
        with pytest.raises(expected):
            hex_encode_abi_type(abi_type, value)
        return

    actual = hex_encode_abi_type(abi_type, value)
    assert actual == expected


@given(st.one_of(st.integers(), st.booleans(), st.binary()))
@example(b'')
def test_hexstr_if_str_passthrough(val):
    to_type = Mock(return_value='zoot')
    assert hexstr_if_str(to_type, val) == 'zoot'
    assert to_type.call_args == ((val, ), {'hexstr': None})


def test_hexstr_if_str_curried():
    converter = hexstr_if_str(to_hex)
    assert converter(255) == '0xff'


@given(hexstr_strategy())
@example('0x')
@example('0')