Python hypothesis.example() Examples

The following are 19 code examples of hypothesis.example(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module hypothesis , or try the search function .
Example #1
Source File: test_utils.py    From matchpy with MIT License 6 votes vote down vote up
def test_cached_property():
    class A:
        call_count = 0

        @cached_property
        def example(self):
            """Docstring Test"""
            A.call_count += 1
            return 42

    a = A()
    b = A()

    assert A.call_count == 0
    assert a.example == 42
    assert A.call_count == 1
    assert a.example == 42
    assert A.call_count == 1
    assert b.example == 42
    assert A.call_count == 2
    assert b.example == 42
    assert A.call_count == 2
    assert A.example.__doc__ == "Docstring Test" 
Example #2
Source File: test_utils.py    From matchpy with MIT License 6 votes vote down vote up
def test_slot_cached_property():
    class A:
        __slots__ = ('cache', )
        call_count = 0

        @slot_cached_property('cache')
        def example(self):
            """Docstring Test"""
            A.call_count += 1
            return 42

    a = A()
    b = A()

    assert A.call_count == 0
    assert a.example == 42
    assert A.call_count == 1
    assert a.example == 42
    assert A.call_count == 1
    assert b.example == 42
    assert A.call_count == 2
    assert b.example == 42
    assert A.call_count == 2
    assert A.example.__doc__ == "Docstring Test" 
Example #3
Source File: test_matching.py    From xapi-profiles with Apache License 2.0 6 votes vote down vote up
def pattern_to_statements(pattern):
    if isinstance(pattern, template):
        return lists(just(pattern), min_size=1, max_size=1)
    rule, value = pattern
    if rule == 'sequence':
        return tuples(*map(pattern_to_statements, value)).map(unpack_list).map(list)
    elif rule == 'alternates':
        return one_of(*map(pattern_to_statements, value))
    elif rule == 'zeroOrMore':
        return lists(pattern_to_statements(value)).map(unpack_list).map(list)
    elif rule == 'oneOrMore':
        return lists(pattern_to_statements(value), min_size=1).map(unpack_list).map(list)
    elif rule == 'optional':
        return lists(pattern_to_statements(value), min_size=0, max_size=1).map(unpack_list).map(list)
    else:
        raise Exception("impossible!", rule)



# this replicates the current scorm pattern, a realistic example of medium
# complexity. Note it has repeated elements, just not in ambiguous ways. 
Example #4
Source File: test_crashes.py    From schemathesis with MIT License 6 votes vote down vote up
def mocked_schema():
    """Module-level mock for fast hypothesis tests.

    We're checking the input validation part, what comes from the network is not important in this context,
    the faster run will be, the better.
    """
    response = Response()
    response._content = b"""openapi: 3.0.0
info:
  title: Sample API
  description: API description in Markdown.
  version: 1.0.0
paths: {}
servers:
  - url: https://api.example.com/{basePath}
    variables:
      basePath:
        default: v1
"""
    response.status_code = 200
    with mock.patch("schemathesis.loaders.requests.sessions.Session.send", return_value=response):
        yield 
Example #5
Source File: test_service.py    From txacme with MIT License 6 votes vote down vote up
def test_registration_email(self):
        """
        If we give our service an email address, that address will be used as a
        registration contact.
        """
        # First the case with no email given.
        with AcmeFixture() as fixture:
            fixture.service.startService()
            self.assertThat(fixture.service._regr, MatchesStructure(
                body=MatchesStructure(
                    key=Is(None),
                    contact=Equals(()))))

        # Next, we give an email.
        with AcmeFixture(email=u'example@example.com') as fixture:
            fixture.service.startService()
            self.assertThat(fixture.service._regr, MatchesStructure(
                body=MatchesStructure(
                    key=Is(None),
                    contact=Equals((u'mailto:example@example.com',))))) 
Example #6
Source File: simple_selection_test.py    From SOL with MIT License 5 votes vote down vote up
def pptc():
    """
    An example paths per traffic class
    """
    # get a complete topology
    topo = complete_topology(5)
    # generate a dummy TM and traffic classes
    tm = tmgen.models.uniform_tm(5, 20, 50, 1)
    tc = traffic_classes(tm, {u'all': 1}, as_dict=False)
    # generate all possibe paths
    res = generate_paths_tc(topo, tc, null_predicate, 10, numpy.inf)
    return res


# Set shortest selection with a variety of values, including one example value 
Example #7
Source File: core.py    From dataclasses-json with MIT License 5 votes vote down vote up
def examples(*args):
    """A variadic `examples` decorator to both supplant stacking of @example
    and support iterables being passed in directly
    """

    def examples_decorator(f):
        g = f
        for arg in args:
            g = example(arg)(g)
        return g

    return examples_decorator 
Example #8
Source File: test_huffman.py    From hpack with MIT License 5 votes vote down vote up
def test_request_huffman_encode(self):
        encoder = HuffmanEncoder(REQUEST_CODES, REQUEST_CODES_LENGTH)
        assert (
            encoder.encode(b"www.example.com") ==
            b'\xf1\xe3\xc2\xe5\xf2:k\xa0\xab\x90\xf4\xff'
        )
        assert encoder.encode(b"no-cache") == b'\xa8\xeb\x10d\x9c\xbf'
        assert encoder.encode(b"custom-key") == b'%\xa8I\xe9[\xa9}\x7f'
        assert (
            encoder.encode(b"custom-value") == b'%\xa8I\xe9[\xb8\xe8\xb4\xbf'
        ) 
Example #9
Source File: test_huffman.py    From hpack with MIT License 5 votes vote down vote up
def test_request_huffman_decoder(self):
        assert (
            decode_huffman(b'\xf1\xe3\xc2\xe5\xf2:k\xa0\xab\x90\xf4\xff') ==
            b"www.example.com"
        )
        assert decode_huffman(b'\xa8\xeb\x10d\x9c\xbf') == b"no-cache"
        assert decode_huffman(b'%\xa8I\xe9[\xa9}\x7f') == b"custom-key"
        assert (
            decode_huffman(b'%\xa8I\xe9[\xb8\xe8\xb4\xbf') == b"custom-value"
        ) 
Example #10
Source File: test_service.py    From txacme with MIT License 5 votes vote down vote up
def test_timer_errors(self):
        """
        If the timed check fails (for example, because registration fails), the
        error should be caught and logged.
        """
        with AcmeFixture(client=FailingClient()) as fixture:
            fixture.service.startService()
            self.assertThat(
                fixture.service._check_certs(),
                succeeded(Always()))
            self.assertThat(flush_logged_errors(), HasLength(2)) 
Example #11
Source File: test_challenges.py    From txacme with MIT License 5 votes vote down vote up
def _responder_factory(self, zone_name=u'example.com'):
        responder = LibcloudDNSResponder.create(
            reactor=SynchronousReactorThreads(),
            driver_name='dummy',
            username='ignored',
            password='ignored',
            zone_name=zone_name,
            settle_delay=0.0)
        if zone_name is not None:
            responder._driver.create_zone(zone_name)
        responder._thread_pool, self._perform = createMemoryWorker()
        return responder 
Example #12
Source File: test_challenges.py    From txacme with MIT License 5 votes vote down vote up
def test_start_responding(self, token):
        """
        Calling ``start_responding`` makes an appropriate resource available.
        """
        challenge = challenges.HTTP01(token=token)
        response = challenge.response(RSA_KEY_512)

        responder = HTTP01Responder()

        challenge_resource = Resource()
        challenge_resource.putChild(b'acme-challenge', responder.resource)
        root = Resource()
        root.putChild(b'.well-known', challenge_resource)
        client = StubTreq(root)

        encoded_token = challenge.encode('token')
        challenge_url = URL(host=u'example.com', path=[
            u'.well-known', u'acme-challenge', encoded_token]).asText()

        self.assertThat(client.get(challenge_url),
                        succeeded(MatchesStructure(code=Equals(404))))

        responder.start_responding(u'example.com', challenge, response)
        self.assertThat(client.get(challenge_url), succeeded(MatchesAll(
            MatchesStructure(
                code=Equals(200),
                headers=AfterPreprocessing(
                    methodcaller('getRawHeaders', b'content-type'),
                    Equals([b'text/plain']))),
            AfterPreprocessing(methodcaller('content'), succeeded(
                Equals(response.key_authorization.encode('utf-8'))))
        )))

        # Starting twice before stopping doesn't break things
        responder.start_responding(u'example.com', challenge, response)
        self.assertThat(client.get(challenge_url),
                        succeeded(MatchesStructure(code=Equals(200))))

        responder.stop_responding(u'example.com', challenge, response)
        self.assertThat(client.get(challenge_url),
                        succeeded(MatchesStructure(code=Equals(404)))) 
Example #13
Source File: test_challenges.py    From txacme with MIT License 5 votes vote down vote up
def test_start_responding(self, token):
        """
        Calling ``start_responding`` makes an appropriate entry appear in the
        host map.
        """
        ckey = RSA_KEY_512_RAW
        challenge = challenges.TLSSNI01(token=token)
        response = challenge.response(RSA_KEY_512)
        server_name = response.z_domain.decode('ascii')
        host_map = {}
        responder = TLSSNI01Responder()
        responder._generate_private_key = lambda key_type: ckey
        wrapped_host_map = responder.wrap_host_map(host_map)

        self.assertThat(wrapped_host_map, Not(Contains(server_name)))
        responder.start_responding(u'example.com', challenge, response)
        self.assertThat(
            wrapped_host_map.get(server_name.encode('utf-8')).certificate,
            MatchesPredicate(response.verify_cert, '%r does not verify'))

        # Starting twice before stopping doesn't break things
        responder.start_responding(u'example.com', challenge, response)
        self.assertThat(
            wrapped_host_map.get(server_name.encode('utf-8')).certificate,
            MatchesPredicate(response.verify_cert, '%r does not verify'))

        responder.stop_responding(u'example.com', challenge, response)
        self.assertThat(wrapped_host_map, Not(Contains(server_name))) 
Example #14
Source File: test_challenges.py    From txacme with MIT License 5 votes vote down vote up
def test_stop_responding_already_stopped(self, token):
        """
        Calling ``stop_responding`` when we are not responding for a server
        name does nothing.
        """
        challenge = self._challenge_factory(token=token)
        response = challenge.response(RSA_KEY_512)
        responder = self._responder_factory()
        d = maybeDeferred(
            responder.stop_responding,
            u'example.com',
            challenge,
            response)
        self._do_one_thing()
        self.assertThat(d, succeeded(Always())) 
Example #15
Source File: test_crashes.py    From schemathesis with MIT License 5 votes vote down vote up
def csv_strategy(enum):
    return st.lists(st.sampled_from([item.name for item in enum]), min_size=1).map(",".join)


# The following strategies generate CLI parameters, for example "--workers=5" or "--exitfirst" 
Example #16
Source File: _hypothesis.py    From schemathesis with MIT License 5 votes vote down vote up
def add_examples(test: Callable, endpoint: Endpoint, hook_dispatcher: Optional[HookDispatcher] = None) -> Callable:
    """Add examples to the Hypothesis test, if they are specified in the schema."""
    examples: List[Case] = [get_single_example(strategy) for strategy in endpoint.get_strategies_from_examples()]
    context = HookContext(endpoint)  # context should be passed here instead
    GLOBAL_HOOK_DISPATCHER.dispatch("before_add_examples", context, examples)
    endpoint.schema.hooks.dispatch("before_add_examples", context, examples)
    if hook_dispatcher:
        hook_dispatcher.dispatch("before_add_examples", context, examples)
    for example in examples:
        test = hypothesis.example(case=example)(test)
    return test 
Example #17
Source File: test_healpy.py    From astropy-healpix with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_ang2vec(lon, lat, lonlat):
    if lonlat:
        theta, phi = lon, lat
    else:
        theta, phi = np.pi / 2. - np.radians(lat), np.radians(lon)
    xyz1 = hp_compat.ang2vec(theta, phi, lonlat=lonlat)
    xyz2 = hp.ang2vec(theta, phi, lonlat=lonlat)
    assert_allclose(xyz1, xyz2, atol=1e-10)


# The following fails, need to investigate:
# @example(nside_pow=29, lon=1.0000000028043134e-05, lat=1.000000000805912e-05,
# nest=False, lonlat=False)
# 
Example #18
Source File: test_configtypes.py    From qutebrowser with GNU General Public License v3.0 5 votes vote down vote up
def test_to_py_valid(self, klass):
        pattern = 'http://*.example.com/'
        assert klass().to_py(pattern) == urlmatch.UrlPattern(pattern) 
Example #19
Source File: test_service.py    From txacme with MIT License 4 votes vote down vote up
def test_time_marches_on(self):
        """
        Any certs that have exceeded the panic or reissue intervals will be
        reissued at the next check.
        """
        now = datetime(2000, 1, 1, 0, 0, 0)
        certs = {
            u'example.com': _generate_cert(
                u'example.com',
                not_valid_before=now - timedelta(seconds=1),
                not_valid_after=now + timedelta(days=31)),
            u'example.org': _generate_cert(
                u'example.org',
                not_valid_before=now - timedelta(seconds=1),
                not_valid_after=now + timedelta(days=32)),
            }
        with AcmeFixture(now=now, certs=certs) as fixture:
            fixture.service.startService()
            self.assertThat(
                fixture.service.when_certs_valid(),
                succeeded(Is(None)))
            self.assertThat(
                fixture.cert_store.as_dict(),
                succeeded(Equals(certs)))

            fixture.clock.advance(36 * 60 * 60)
            self.assertThat(
                fixture.cert_store.as_dict(),
                succeeded(
                    MatchesDict({
                        u'example.com': Not(Equals(certs[u'example.com'])),
                        u'example.org': Equals(certs[u'example.org']),
                        })))
            self.assertThat(fixture.responder.challenges, HasLength(0))

            fixture.clock.advance(36 * 60 * 60)
            self.assertThat(
                fixture.cert_store.as_dict(),
                succeeded(
                    MatchesDict({
                        u'example.com': Not(Equals(certs[u'example.com'])),
                        u'example.org': Not(Equals(certs[u'example.org'])),
                        })))
            self.assertThat(fixture.responder.challenges, HasLength(0))