Exemplo n.º 1
0
def host_json():
    return st.fixed_dictionaries(
        {
            "metadata":
                st.fixed_dictionaries({
                    "update_time": st.floats(),
                    "update_user": st.one_of(st.none(), st.text()),
                    "update_action": st.integers(),
                    "creator": st.text(),
                    "create_time": st.integers(),
                    "update_controller_action": st.text(),
                    "owner": st.one_of(st.none(), st.text()),
                    "command_id": st.one_of(st.none(), st.text(), st.integers()),}),
            "name": st.one_of(st.none(), st.text()),
            "ip": st.one_of(st.none(), st.text()),
            "_rev": st.one_of(st.none(), st.text()),
            "description": st.one_of(st.none(), st.text()),
            "default_gateway": st.one_of(st.none(), st.text()),
            "owned": st.booleans(),
            "services": st.one_of(st.none(), st.integers()),
            "hostnames": st.lists(st.text()),
            "vulns": st.one_of(st.none(), st.integers()),
            "owner": st.one_of(st.none(), st.text()),
            "credentials": st.one_of(st.none(), st.integers()),
            "_id": st.one_of(st.none(), st.integers()),
            "os": st.one_of(st.none(), st.text()),
            "id": st.one_of(st.none(), st.integers()),
            "icon": st.one_of(st.none(), st.text())}
    )
Exemplo n.º 2
0
def api_results(min_size=0, max_size=20, hook_types=None):
    count = integers(min_value=min_size, max_value=max_size).example()
    hook_types = hook_types or get_hook_names()

    return fixed_dictionaries(
        {
            "count": just(count),
            "next": none(),
            "prev": none(),
            "results": lists(
                fixed_dictionaries(
                    {
                        "name": text(min_size=1),
                        "latest_version": integers(min_value=0),
                        "content": fixed_dictionaries(
                            {
                                "hook_type": sampled_from(hook_types),
                                "version": integers(min_value=0),
                                "description": text(min_size=1),
                                "download_url": text(min_size=1),
                                "checksum": text(min_size=1),
                            }
                        ),
                    }
                ),
                min_size=count,
                max_size=count,
            ),
        }
    )
Exemplo n.º 3
0
def jenkins_build_results(inQueue=None, builds=None):
    """Create a strategy for generating Jenkins API information for a job.

    :param strategy inQueue: strategy for the inQueue key, or None to use
        the default.
    :param strategy builds: strategy for populating the builds key, or None
        for the default. The special value `NO_BUILDS` will mean that the
        builds key is not in the resulting dict at all.
    :return strategy: a strategy.
    """
    strats = []
    if inQueue is None:
        inQueue = booleans()
        strats.append(just(pmap()))
    without_builds = fixed_dictionaries(dict(
        inQueue=inQueue))
    if builds is None or builds is NO_BUILDS:
        strats.append(without_builds)
    if builds is None:
        builds = lists(jenkins_builds, average_size=1)
    if builds is not NO_BUILDS:
        with_builds = fixed_dictionaries(dict(
            inQueue=inQueue,
            builds=builds,
            property=dictionaries(
                text(max_size=2), text(max_size=2),
                average_size=1, max_size=2)))
        strats.append(with_builds)
    return one_of(*strats)
Exemplo n.º 4
0
def get_request(data, spec, spec_host):
    endpoint_path = data.draw(st.sampled_from(spec['paths'].keys()))
    endpoint = spec['paths'][endpoint_path]

    method_name = data.draw(st.sampled_from(endpoint.keys()))
    endpoint = endpoint[method_name]

    path_params = _get_filtered_parameter(endpoint, 'path', spec)
    path_args = data.draw(st.fixed_dictionaries(path_params))

    query_params = _get_filtered_parameter(endpoint, 'query', spec)
    query_args = data.draw(st.fixed_dictionaries(query_params))

    body_params = _get_filtered_parameter(endpoint, 'body', spec)
    if body_params:
        body_args = data.draw(body_params['body'])
    else:
        body_args = None

    valid_request_body_format = get_item_path_acceptable_format(endpoint, spec)

    request_data = None
    request_headers = {}

    if body_args:
        # no_body_format_declaration(body_args, valid_request_body_format, endpoint)
        if body_args and valid_request_body_format is None:
            # Force a request format, swagger ui seems to force json format
            valid_request_body_format = ["application/json"]

        request_body_format = data.draw(st.sampled_from(valid_request_body_format), 'request_body_format')

        request_headers['Content-Type'] = request_body_format
        if request_body_format == 'application/x-www-form-urlencoded':
            request_data = body_args
        elif request_body_format == 'application/json':
            request_data = json.dumps(body_args, cls=CustomJsonEncoder)
        elif request_body_format == 'application/xml':
            pass
            # TODO Implement XML
        else:
            raise Exception(request_body_format)

    endpoint_url = endpoint_path.format(**path_args)
    assume('\x00' not in endpoint_url)

    # Generate request
    URL = furl(spec_host)
    URL = URL.join(endpoint_url.lstrip('/'))

    if query_args:
        URL = URL.add(args=query_args)

    request = Request(method_name, URL.url, data=request_data,
                      headers=request_headers).prepare()
    request.build_context = locals()
    return request
Exemplo n.º 5
0
 def visit_structure(self, shape):
     if shape.name in self.active:
         return strategies.fixed_dictionaries({})
     self.active.add(shape.name)
     try:
         structure = {}
         for member in shape.iter_members():
             structure[member.name] = self.visit(member.shape)
         return strategies.fixed_dictionaries(structure)
     finally:
         self.active.remove(shape.name)
Exemplo n.º 6
0
def objects(elements=None, *,
            required_fields=None,
            optional_fields=None,
            min_size=None,
            average_size=None,
            max_size=None):
    """Returns a strategy that generates dicts of specified `elements`.

    The `elements` must be valid Hypothesis strategy. The keys are ensured to
    be string only as JSON requires.

    While choice of `elements` left here for user side, it's not recommended to
    use anything that produces non-serializable to JSON values.

    Also possible to ensure that some fields with values generated by a certain
    strategy are always exists (`required_fields`) or just optional
    (`optional_fields`).
    """
    def check_type(varname, var, expected):
        if not isinstance(var, expected):
            raise TypeError('{} must be {}, got {}'.format(
                varname, expected, type(var)))

    acc = []
    if required_fields:
        check_type('required_fields', required_fields, dict)
        for key in required_fields:
            check_type('required field name', key, str)
        acc.append(st.fixed_dictionaries(required_fields))

    if optional_fields:
        check_type('optional_fields', optional_fields, dict)
        for key in optional_fields:
            check_type('optional field name', key, str)
        acc.append(st.sets(st.sampled_from(optional_fields)).flatmap(
            lambda keys: st.fixed_dictionaries({key: optional_fields[key]
                                                for key in keys})))
    if elements:
        acc.append(st.dictionaries(strings(), elements,
                                   min_size=min_size,
                                   average_size=average_size,
                                   max_size=max_size))

    if not acc:
        raise RuntimeError('object must have any strategy for fields')

    return st.tuples(*reversed(acc)).map(
        lambda s: reduce(lambda a, d: dict(a, **d), s))
def test_ordered_dictionaries_preserve_keys():
    r = Random()
    keys = list(range(100))
    r.shuffle(keys)
    x = fixed_dictionaries(
        OrderedDict([(k, booleans()) for k in keys])).example()
    assert list(x.keys()) == keys
Exemplo n.º 8
0
def models(
    model,  # type: Type[dm.Model]
    **field_strategies  # type: Union[st.SearchStrategy[Any], DefaultValueType]
):
    # type: (...) -> st.SearchStrategy[Any]
    """Return a strategy for examples of ``model``.

    .. warning::
        Hypothesis creates saved models. This will run inside your testing
        transaction when using the test runner, but if you use the dev console
        this will leave debris in your database.

    ``model`` must be an subclass of :class:`~django:django.db.models.Model`.
    Strategies for fields may be passed as keyword arguments, for example
    ``is_staff=st.just(False)``.

    Hypothesis can often infer a strategy based the field type and validators
    - for best results, make sure your validators are derived from Django's
    and therefore have the known types and attributes.
    Passing a keyword argument skips inference for that field; pass a strategy
    or pass ``hypothesis.extra.django.models.default_value`` to skip
    inference for that field.

    Foreign keys are not automatically derived. If they're nullable they will
    default to always being null, otherwise you always have to specify them.
    For example, examples of a Shop type with a foreign key to Company could
    be generated with::

      shop_strategy = models(Shop, company=models(Company))
    """
    result = {}
    for k, v in field_strategies.items():
        if not isinstance(v, DefaultValueType):
            result[k] = v
    missed = []  # type: List[Text]
    for f in model._meta.concrete_fields:
        if not (f.name in field_strategies or isinstance(f, dm.AutoField)):
            result[f.name] = _get_strategy_for_field(f)
            if result[f.name].is_empty:
                missed.append(f.name)
    if missed:
        raise InvalidArgument(
            u'Missing arguments for mandatory field%s %s for model %s'
            % (u's' if missed else u'', u', '.join(missed), model.__name__))

    for field in result:
        if model._meta.get_field(field).primary_key:
            # The primary key is generated as part of the strategy. We
            # want to find any existing row with this primary key and
            # overwrite its contents.
            kwargs = {field: result.pop(field)}
            kwargs['defaults'] = st.fixed_dictionaries(result)
            return _models_impl(
                st.builds(model.objects.update_or_create, **kwargs)
            )

    # The primary key is not generated as part of the strategy, so we
    # just match against any row that has the same value for all
    # fields.
    return _models_impl(st.builds(model.objects.get_or_create, **result))
Exemplo n.º 9
0
def url(schemes=[], userpass=False, port=False, url=False, query=False,
        fragment=False):

    if schemes:
        scheme = st.just(random.choice(schemes))
    else:
        scheme = st.text(alphabet=ascii_lowercase+digits, min_size=2)

    d = {'scheme': scheme,
         'domain': st.lists(
             st.text(
                 alphabet=ascii_lowercase + digits,
                 min_size=1,
                 max_size=63),
             min_size=1,
             max_size=3),
         'tld': st.text(alphabet=ascii_lowercase, min_size=2, max_size=63)}

    if userpass:
        d['user'] = st.text(alphabet=ascii_lowercase + digits)
        d['passwd'] = st.text(alphabet=ascii_lowercase + digits)
    if port:
        d['port'] = st.integers(min_value=0, max_value=65535)
    if url:
        d['url'] = st.lists(st.text())
    if query:
        d['query'] = st.lists(st.tuples(
            st.text(alphabet=ascii_lowercase, min_size=1),
            st.text(alphabet=ascii_lowercase + digits, min_size=1)))
    if fragment:
        d['fragment'] = st.text()

    urlst = strategy(st.fixed_dictionaries(d))

    return urlst.map(to_url).filter(max_len)
Exemplo n.º 10
0
def builder(factories, bravais_lattices=BravaisLattice):
    '''
    Return a hypothesis.strategies.fixed_dictionaries containing
    lattice primitive cells

    Parameters
    ----------
    factories: dict
        {BravaisLattice(IntEnum): (PrimitiveCell.<factory_function>,
                                   hypothesis.strategies.tuples)}
    bravais_lattices: iterable
        iterable of BravaisLattice(IntEnum) for selecting a subset of
        BravaisLattice.  Default: all BravaisLattice

    Returns
    -------
    lattice: fixed_dictionary
        {BravaisLattice(IntEnum): PrimitiveCell}
    '''

    @composite
    def builds_unpack(draw, factory, elements):
        ''' Similar to hypothesis.strategies.builds except
        it unpacks the arguments '''
        args = elements.example()
        return factory(*args)

    lattices = {}
    for bravais_lattice in bravais_lattices:
        factory, elements = factories[bravais_lattice]
        lattices[bravais_lattice] = builds_unpack(factory, elements)

    return fixed_dictionaries(lattices)
Exemplo n.º 11
0
def header(header_class, **kwargs):
    """Create a strategy for producing headers of a specific class.

    Args:
        header_class: The type of header to be produced. This class will be
            introspected to determine suitable strategies for each named
            field.

        **kwargs: Any supplied keyword arguments can be used to fix the value
            of particular header fields.
    """

    field_strategies = {}
    for field_name in header_class.ordered_field_names():
        if field_name in kwargs:
            field_strategy = just(kwargs.pop(field_name))
        else:
            value_type = getattr(header_class, field_name).value_type
            field_strategy = integers(value_type.MINIMUM, value_type.MAXIMUM)
        field_strategies[field_name] = field_strategy

    if len(kwargs) > 0:
        raise TypeError("Unrecognised binary header field names {} for {}".format(
            ', '.join(kwargs.keys()),
            header_class.__name__))

    return fixed_dictionaries(field_strategies) \
        .map(lambda kw: header_class(**kw))
def brief_data(essential_count=5, nice_to_have_count=5):
    return fixed_dictionaries({
        'specialistRole': just('developer'),
        'location': lists(elements=just(['ACT'])),
        'essentialRequirements': requirements_list(essential_count),
        'niceToHaveRequirements': requirements_list(nice_to_have_count),
    })
def brief_data(essential_count=5, nice_to_have_count=5):
    return fixed_dictionaries({
        'specialistRole': just('developer'),
        'location': text(min_size=1, average_size=10, alphabet='abcdefghijkl'),
        'essentialRequirements': requirements_list(essential_count),
        'niceToHaveRequirements': requirements_list(nice_to_have_count),
    })
def brief_response_data(essential_count=5, nice_to_have_count=5):
    return fixed_dictionaries({
        "essentialRequirements": requirements_list(essential_count, answers=True),
        "niceToHaveRequirements": requirements_list(nice_to_have_count, answers=True),
        "availability": text(min_size=1, average_size=10, alphabet='abcdefghijkl'),
        "respondToEmailAddress": just("*****@*****.**"),
    })
def brief_response_data(essential_count=5, nice_to_have_count=5):
    return fixed_dictionaries({
        "essentialRequirements": requirements_list(essential_count, answers=True),
        "niceToHaveRequirements": requirements_list(nice_to_have_count, answers=True),
        "availability": _brief_response_availability,
        "respondToEmailAddress": just("*****@*****.**"),
    })
def specialists_brief_response_data(min_day_rate=1, max_day_rate=1000):
    return fixed_dictionaries({
        "essentialRequirements": requirements_list(5, answers=True),
        "niceToHaveRequirements": requirements_list(5, answers=True),
        "respondToEmailAddress": just("*****@*****.**"),
        "availability": _brief_response_availability,
        "dayRate": integers(min_value=min_day_rate, max_value=max_day_rate).map(lambda x: str(x)),
    })
Exemplo n.º 17
0
def builds_ignoring_invalid(target, *args, **kwargs):
    def splat(value):
        try:
            return target(*value[0], **value[1])
        except InvalidArgument:
            assume(False)
    return st.tuples(
        st.tuples(*args), st.fixed_dictionaries(kwargs)).map(splat)
Exemplo n.º 18
0
    def steps(self):
        # Pick initialize rules first
        if self._initialize_rules_to_run:
            return one_of([
                tuples(just(rule), fixed_dictionaries(rule.arguments))
                for rule in self._initialize_rules_to_run
            ])

        return self.__rules_strategy
Exemplo n.º 19
0
def license_json():
    return st.fixed_dictionaries(
        {
            "lictype": st.one_of(st.none(), st.text()),
            "metadata": st.fixed_dictionaries({
                "update_time": st.floats(),
                "update_user": st.one_of(st.none(), st.text()),
                "update_action": st.integers(),
                "creator": st.one_of(st.none(), st.text()),
                "create_time": st.floats(),
                "update_controller_action": st.one_of(st.none(), st.text()),
            "owner": st.one_of(st.none(), st.text())}),
            "notes": st.one_of(st.none(), st.text()),
            "product": st.one_of(st.none(), st.text()),
            "start": st.datetimes(),
            "end": st.datetimes(),
            "type": st.one_of(st.none(), st.text())
         })
Exemplo n.º 20
0
def builds_ignoring_invalid(target, *args, **kwargs):
    def splat(value):
        try:
            result = target(*value[0], **value[1])
            result.validate()
            return result
        except InvalidArgument:
            reject()
    return st.tuples(
        st.tuples(*args), st.fixed_dictionaries(kwargs)).map(splat)
Exemplo n.º 21
0
def from_attrs(target, args, kwargs, to_infer):
    """An internal version of builds(), specialised for Attrs classes."""
    fields = attr.fields(target)
    kwargs = {k: v for k, v in kwargs.items() if v is not infer}
    for name in to_infer:
        kwargs[name] = from_attrs_attribute(getattr(fields, name), target)
    # We might make this strategy more efficient if we added a layer here that
    # retries drawing if validation fails, for improved composition.
    # The treatment of timezones in datetimes() provides a precedent.
    return st.tuples(st.tuples(*args), st.fixed_dictionaries(kwargs)).map(
        lambda value: target(*value[0], **value[1]))
Exemplo n.º 22
0
 def build(tag):
     args = {
         invariant.tag_attribute: just(tag),
     }
     args.update({
         attribute: strategy
         for attribute, strategy in attr_strategies.items()
         if (attribute in invariant.attributes_for_tag[tag] or
             attribute not in invariant._all_attributes)
     })
     return fixed_dictionaries(args).map(lambda kwargs: type_(**kwargs))
Exemplo n.º 23
0
 def visit_map(self, shape):
     if shape.name in self.active:
         return strategies.fixed_dictionaries({})
     self.active.add(shape.name)
     try:
         return strategies.dictionaries(
             keys=self.visit(shape.key_shape),
             values=self.visit(shape.value_shape),
         )
     finally:
         self.active.remove(shape.name)
Exemplo n.º 24
0
def email_events():
    return st.builds(hyp3_events.EmailEvent,
                     user_id=st.integers(),
                     sub_id=st.integers(),
                     granule_name=granules(),
                     additional_info=st.lists(
                         st.fixed_dictionaries({
                             'name': st.text(),
                             'value': st.text()
                         })),
                     browse_url=urls(),
                     download_url=urls())
Exemplo n.º 25
0
def nested_checkboxes(draw, options_list_strategy=None,
                      optional_keys=st.lists(st.sampled_from(['value', 'description']))):
    option = {
        'label': st.text()
    }
    for k in draw(optional_keys):
        option[k] = st.text()

    if options_list_strategy is not None:
        option['options'] = options_list_strategy

    return draw(st.fixed_dictionaries(option))
Exemplo n.º 26
0
def from_attrs(target, args, kwargs, to_infer):
    """An internal version of builds(), specialised for Attrs classes."""
    fields = attr.fields(target)
    kwargs = {k: v for k, v in kwargs.items() if v is not infer}
    for name in to_infer:
        kwargs[name] = from_attrs_attribute(getattr(fields, name), target)
    # We might make this strategy more efficient if we added a layer here that
    # retries drawing if validation fails, for improved composition.
    # The treatment of timezones in datetimes() provides a precedent.
    return st.tuples(st.tuples(*args), st.fixed_dictionaries(kwargs)).map(
        lambda value: target(*value[0], **value[1])
    )
Exemplo n.º 27
0
def sparse_xent_params(draw):
    num_classes = draw(hps.integers(1, 6))
    batch_shape = draw(shapes(min_dims=1))
    labels = single_arrays(batch_shape=batch_shape,
                           shape=hps.just(tuple()),
                           dtype=np.int32,
                           elements=hps.integers(0, num_classes - 1))
    logits = single_arrays(batch_shape=batch_shape,
                           shape=hps.just((num_classes, )),
                           elements=hps.floats(min_value=-1e5, max_value=1e5))
    return draw(
        hps.fixed_dictionaries(dict(labels=labels, logits=logits)).map(Kwargs))
Exemplo n.º 28
0
 def gen_basic_event(self, event_type, additional_map):
     "TODO"
     base_map = {
         'start_time':
         integers(min_value=self.current_time,
                  max_value=self.time_window_length + self.current_time),
         'event_length':
         integers(min_value=1, max_value=self.time_window_length)
     }
     base_map.update(additional_map)
     return fixed_dictionaries(base_map).flatmap(
         lambda x: just(event_type(x)))
Exemplo n.º 29
0
def annotation_strategy():
    """
    Build a strategy to generate data for an introspection annotation.
    """
    return builds(
        Annotation,
        fixed_dictionaries({
            "name": _TEXT_STRATEGY,
            "value": _TEXT_STRATEGY
        }),
        just(frozenset()),
    )
Exemplo n.º 30
0
def xent_params(draw):
  num_classes = draw(hps.integers(1, 6))
  batch_shape = draw(shapes(min_dims=1))
  labels = batched_probabilities(  # pylint:disable=no-value-for-parameter
      batch_shape=batch_shape, num_classes=num_classes)
  logits = single_arrays(
      batch_shape=batch_shape,
      shape=hps.just((num_classes,)),
      elements=hps.floats(min_value=-1e5, max_value=1e5))
  return draw(
      hps.fixed_dictionaries(dict(
          labels=labels, logits=logits)).map(Kwargs))
Exemplo n.º 31
0
 def __attrs_post_init__(self):
     arguments = {}
     bundles = []
     for k, v in sorted(self.arguments.items()):
         assert not isinstance(v, BundleReferenceStrategy)
         if isinstance(v, Bundle):
             bundles.append(v)
             arguments[k] = BundleReferenceStrategy(v.name)
         else:
             arguments[k] = v
     self.bundles = tuple(bundles)
     self.arguments_strategy = fixed_dictionaries(arguments)
Exemplo n.º 32
0
 def __attrs_post_init__(self):
     arguments = {}
     bundles = []
     for k, v in sorted(self.arguments.items()):
         assert not isinstance(v, BundleReferenceStrategy)
         if isinstance(v, Bundle):
             bundles.append(v)
             arguments[k] = BundleReferenceStrategy(v.name)
         else:
             arguments[k] = v
     self.bundles = tuple(bundles)
     self.arguments_strategy = fixed_dictionaries(arguments)
Exemplo n.º 33
0
def account(draw):
    return draw(
        fixed_dictionaries({
            'id':
            text(alphabet=digits, min_size=3, max_size=4),
            'alias':
            text(alphabet=ascii_letters + digits, min_size=1, max_size=3),
            'role':
            text(alphabet=ROLE_SAFE_ALPHABET, min_size=1, max_size=3),
            'region':
            text(alphabet=ascii_letters + digits, min_size=1, max_size=3),
        }))
Exemplo n.º 34
0
    def generate_network_fault_only(draw):

        fault = {
            "limit": draw(NetworkFaultGen.generate_limit()),
            "delay": draw(NetworkFaultGen.generate_delay()),
            "loss_random": draw(NetworkFaultGen.generate_loss_random()),
            "corrupt": draw(NetworkFaultGen.generate_corrupt()),
            "duplicate": draw(NetworkFaultGen.generate_duplicate()),
            #            "reorder": draw(NetworkFaultGen.generate_reorder()),
            "rate": draw(NetworkFaultGen.generate_rate()),
        }

        return st.fixed_dictionaries(fault)
Exemplo n.º 35
0
 def generate_delay(draw):
     delay = {
         "time":
         st.integers(min_value=NetworkFaultGen.ms_min,
                     max_value=NetworkFaultGen.ms_max),
         "jitter":
         st.one_of(st.integers(min_value=0, max_value=5000), st.none()),
         "correlation":
         st.one_of(st.integers(min_value=0, max_value=100), st.none()),
         "distribution":
         st.one_of(st.just("normal"), st.none())
     }
     return st.one_of(st.fixed_dictionaries(delay), st.none())
Exemplo n.º 36
0
def plot_kwargs() -> st.SearchStrategy[Dict[str, Any]]:
    def _filter_key_if_none(d: dict):
        return {k: v for k, v in d.items() if v is not None}

    return st.fixed_dictionaries(
        dict(
            figsize=st.none()
            | st.tuples(*[st.floats(min_value=1, max_value=10)] * 2),
            max_fraction_spent_plotting=st.none() | st.floats(0.0, 1.0),
            last_n_batches=st.none() | st.integers(1, 10),
            nrows=st.none() | st.integers(1, 3),
            ncols=st.none() | st.integers(1, 3),
        )).map(_filter_key_if_none)
Exemplo n.º 37
0
def get_nll_args(*arrs):
    (s, ) = arrs
    y_true = hnp.arrays(
        shape=(s.shape[0], ),
        dtype=hnp.integer_dtypes(),
        elements=st.integers(min_value=0, max_value=s.shape[1] - 1),
    )
    weights = st.none() | hnp.arrays(
        shape=(s.shape[1], ),
        dtype=float,
        elements=st.floats(1e-8, 100),
    )
    return st.fixed_dictionaries(dict(y_true=y_true, weights=weights))
Exemplo n.º 38
0
def test_regression_issue_1230():
    strategy = st.builds(
        lambda x, y: dict(list(x.items()) + list(y.items())),
        st.fixed_dictionaries({"0": st.text()}),
        st.builds(
            lambda dictionary, keys: {key: dictionary[key]
                                      for key in keys},
            st.fixed_dictionaries(
                {"1": st.lists(elements=st.sampled_from(["a"]))}),
            st.sets(elements=st.sampled_from(["1"])),
        ),
    )

    @seed(81581571036124932593143257836081491416)
    @settings(database=None)
    @given(strategy)
    def test_false_is_false(params):
        assume(params.get("0") not in ("", "\x00"))
        raise ValueError()

    with pytest.raises(ValueError):
        test_false_is_false()
Exemplo n.º 39
0
def test_regression_issue_1230():
    strategy = st.builds(
        lambda x, y: dict((list(x.items()) + list(y.items()))),
        st.fixed_dictionaries({'0': st.text()}),
        st.builds(
            lambda dictionary, keys: {key: dictionary[key] for key in keys},
            st.fixed_dictionaries({
                '1': st.lists(elements=st.sampled_from(['a']))
            }),
            st.sets(elements=st.sampled_from(['1']))
        )
    )

    @seed(81581571036124932593143257836081491416)
    @settings(database=None)
    @given(strategy)
    def test_false_is_false(params):
        assume(params.get('0') not in ('', '\x00'))
        raise ValueError()

    with pytest.raises(ValueError):
        test_false_is_false()
def brief_data(essential_count=5, nice_to_have_count=5):
    return fixed_dictionaries({
        'title':
        just('My Test Brief Title'),
        'specialistRole':
        just('developer'),
        'location':
        text(min_size=1, alphabet='abcdefghijkl'),
        'essentialRequirements':
        requirements_list(essential_count),
        'niceToHaveRequirements':
        requirements_list(nice_to_have_count),
    })
Exemplo n.º 41
0
def small_data_arrays_from_type(draw, datatype):
    return draw(
        builds(
            DataArray,
            just(0.0),
            attrs=fixed_dictionaries(
                {
                    "datatype": just(datatype),
                    "transform": trivial_transforms(),
                },
                optional={"provenance": builds(MagicMock())},
            ),
        ))
Exemplo n.º 42
0
def any_call_of_method(draw, method):
    if method == "sample":
        population = draw(seq_param)
        k = draw(st.integers(0, len(population)))
        kwargs = {"population": population, "k": k}
    elif method == "randint":
        a = draw(INT64)
        b = draw(INT64)
        a, b = sorted((a, b))
        kwargs = {"a": a, "b": b}
    elif method == "randrange":
        a = draw(INT64)
        b = draw(INT64)
        assume(a != b)
        a, b = sorted((a, b))
        if a == 0 and sys.version_info[:2] < (3, 10) and draw(st.booleans()):
            start = b
            stop = None
        else:
            start = a
            stop = b

        kwargs = {
            "start": start,
            "stop": stop,
            "step": draw(st.integers(1, 3))
        }
    elif method == "triangular":
        a = normalize_zero(
            draw(st.floats(allow_infinity=False, allow_nan=False)))
        b = normalize_zero(
            draw(st.floats(allow_infinity=False, allow_nan=False)))
        a, b = sorted((a, b))
        if draw(st.booleans()):
            draw(st.floats(a, b))
        else:
            pass
        kwargs = {"low": a, "high": b, "mode": None}
    elif method == "uniform":
        a = normalize_zero(
            draw(st.floats(allow_infinity=False, allow_nan=False)))
        b = normalize_zero(
            draw(st.floats(allow_infinity=False, allow_nan=False)))
        a, b = sorted((a, b))
        kwargs = {"a": a, "b": b}
    else:
        kwargs = draw(st.fixed_dictionaries(METHOD_STRATEGIES[method]))

    args, kwargs = convert_kwargs(method, kwargs)

    return (args, kwargs)
Exemplo n.º 43
0
def method_strategy(
    draw,
    *,
    min_children=0,
    max_children=None,
    min_annotations=0,
    max_annotations=None,
    min_args=0,
    max_args=None,
    dbus_signature_args=None,
):
    """
    Build a strategy to generate data for an introspection method.

    :param min_children: min argument passed to component strategies
    :type min_children: non-negative int
    :param max_children: max argument passed to component strategies
    :type max_children: non-negative int or None
    :param min_annotations: the minimum number of annotation elements
    :type min_annotations: non-negative int
    :param max_annotations: the maximum number of annotation elements
    :type max_annotations: non-negative int or None
    :param min_args: the minimum number of arg elements
    :type min_args: non-negative int
    :param max_args: the maximum number of arg elements
    :type max_args: non-negative int or None
    :param dbus_signature_args: to override dbus_signatures defaults
    :type dbus_signature_args: dict of str * object or NoneType

    min_children and max_children are passed to component element strategies.
    """
    annotations = draw(
        frozensets(
            annotation_strategy(), min_size=min_annotations, max_size=max_annotations
        )
    )
    args = draw(
        frozensets(
            arg_strategy(
                min_children=min_children,
                max_children=max_children,
                dbus_signature_args=dbus_signature_args,
            ),
            min_size=min_args,
            max_size=max_args,
        )
    )
    attrs = draw(fixed_dictionaries({"name": _TEXT_STRATEGY}))

    return Method(attrs, annotations | args)
Exemplo n.º 44
0
def fixed_dict_of_printable_strings(keys, **overrides):
    """Create a strategy for producing a dictionary of strings with specific keys.

    Args:
        keys: A list of keys which the strategy will associate with arbitrary strings.

        **overrides: Specific keywords arguments can be supplied to associate certain keys
            with specific values.  The values supplied via kwargs override any supplied
            through the keys argument.
    """
    d = {key: text(alphabet=PRINTABLE_ASCII_ALPHABET) for key in keys}
    for keyword in overrides:
        d[keyword] = just(overrides[keyword])
    return fixed_dictionaries(d)
 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
Exemplo n.º 46
0
def get_tournament_selection():
    n = hs.integers(min_value=1, max_value=100)
    _n = hs.shared(n, "same")
    _m = hs.shared(n, "same")
    population_size = hs.shared(n, "same")
    tournament_size = _m.flatmap(
        lambda x: hs.integers(min_value=1, max_value=x))
    pop = _n.flatmap(lambda x: get_individuals(hs.just(x)))

    return hs.fixed_dictionaries({
        "population": pop,
        "population_size": population_size,
        "tournament_size": tournament_size
    })
Exemplo n.º 47
0
def start_events():
    return st.builds(
        hyp3_events.StartEvent,
        granule=granules(),
        user_id=st.integers(),
        sub_id=st.integers(),
        output_patterns=st.lists(st.text()),
        script_path=st.text(),
        additional_info=st.lists(
            st.fixed_dictionaries({
                'name': st.text(),
                'value': st.text()
            })),
    )
Exemplo n.º 48
0
def fixed_dict_of_printable_strings(keys, **overrides):
    """Create a strategy for producing a dictionary of strings with specific keys.

    Args:
        keys: A list of keys which the strategy will associate with arbitrary strings.

        **overrides: Specific keywords arguments can be supplied to associate certain keys
            with specific values.  The values supplied via kwargs override any supplied
            through the keys argument.
    """
    d = {key: text(alphabet=PRINTABLE_ASCII_ALPHABET) for key in keys}
    for keyword in overrides:
        d[keyword] = just(overrides[keyword])
    return fixed_dictionaries(d)
Exemplo n.º 49
0
def urls ():
    """ Build http/https URL """
    scheme = st.sampled_from (['http', 'https'])
    # Path must start with a slash
    pathSt = st.builds (lambda x: '/' + x, st.text ())
    args = st.fixed_dictionaries ({
            'scheme': scheme,
            'host': domains (),
            'port': st.one_of (st.none (), st.integers (min_value=1, max_value=2**16-1)),
            'path': pathSt,
            'query_string': st.text (),
            'fragment': st.text (),
            })
    return st.builds (lambda x: URL.build (**x), args)
Exemplo n.º 50
0
    def test_snippet_given(self) -> None:
        @icontract.require(lambda x, y: x < y)
        def some_func(x: float, y: float) -> None:
            pass

        @hypothesis.given(
            st.fixed_dictionaries({"x": st.floats(), "y": st.floats()}).filter(
                lambda d: d["x"] < d["y"]
            )
        )
        def test(kwargs: Mapping[str, Any]) -> None:
            some_func(**kwargs)

        test()
Exemplo n.º 51
0
def specialists_brief_response_data(min_day_rate=1, max_day_rate=1000):
    return fixed_dictionaries({
        "essentialRequirements":
        requirements_list(5, answers=True),
        "niceToHaveRequirements":
        requirements_list(5, answers=True),
        "respondToEmailAddress":
        just("*****@*****.**"),
        "availability":
        text(min_size=1, average_size=10, alphabet='abcdefghijkl'),
        "dayRate":
        integers(min_value=min_day_rate,
                 max_value=max_day_rate).map(lambda x: str(x)),
    })
Exemplo n.º 52
0
 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
Exemplo n.º 53
0
def _to_signature_data(
    names_with_defaults: Tuple[List[str],
                               List[Any]]) -> Strategy[SignatureData]:
    names, defaults = names_with_defaults
    if not names:
        parameters_counters = strategies.builds(OrderedDict)
    elif len(names) == 1:
        kinds = set(inspect._ParameterKind)
        if PRE_PYTHON_3_8:
            kinds -= {inspect._POSITIONAL_ONLY}
        parameters_counters = strategies.sampled_from([
            OrderedDict([(kind, (1, [is_callable]))])
            for kind, is_callable in product(kinds, [False, True])
        ])
    else:
        max_counts = (len(names) - 2) // (2 if PRE_PYTHON_3_8 else 3)
        counts = strategies.integers(0, max_counts)
        variants = OrderedDict()
        if not PRE_PYTHON_3_8:
            variants[inspect._POSITIONAL_ONLY] = counts.flatmap(
                to_count_with_flags)
        variants[inspect._POSITIONAL_OR_KEYWORD] = counts.flatmap(
            to_count_with_flags)
        variants[inspect._VAR_POSITIONAL] = booleans.flatmap(
            to_count_with_flags)
        variants[inspect._KEYWORD_ONLY] = counts.flatmap(to_count_with_flags)
        variants[inspect._VAR_KEYWORD] = booleans.flatmap(to_count_with_flags)
        parameters_counters = strategies.fixed_dictionaries(variants)

    def select(
        counter: Dict[inspect._ParameterKind, Tuple[int, List[bool]]]
    ) -> SignatureData:
        names_iterator = reversed(names)
        defaults_iterator = chain(
            defaults,
            repeat(inspect.Parameter.empty,
                   len(names) - len(defaults)))
        return OrderedDict(
            (kind,
             list(
                 zip(
                     islice(names_iterator, count),
                     repeat(inspect.Parameter.empty, count) if (
                         kind is inspect._VAR_POSITIONAL
                         or kind is inspect._VAR_KEYWORD
                     ) else islice(defaults_iterator, count), flags)))
            for kind, (count, flags) in reversed(counter.items()) if count)

    return parameters_counters.map(select)
Exemplo n.º 54
0
def object_metadatas(model=default_model):
    """
    Build ``v1.ObjectMeta`` without a namespace.
    """
    return builds(
        model.v1.ObjectMeta.create,
        fixed_dictionaries({
            u"name": object_name(),
            u"uid": none(),
            u"labels": one_of(
                none(),
                labels(),
            ),
        }),
    )
def valid_task_update_payload(user_id, target_id):
    return st.fixed_dictionaries({
        "target_id":
        st.just(target_id),
        "user_id":
        st.just(user_id),
        "title":
        st.text(),
        "description":
        st.text(),
        "due_time":
        st.just(datetime.datetime.now().isoformat() + "Z"),
        "completion_time":
        st.just(datetime.datetime.now().isoformat() + "Z"),
    })
Exemplo n.º 56
0
def chromeResponseReceived (reqid, url):
    mimeTypeSt = st.one_of (st.none (), st.just ('text/html'))
    remoteIpAddressSt = st.one_of (st.none (), st.just ('127.0.0.1'))
    protocolSt = st.one_of (st.none (), st.just ('h2'))
    statusCodeSt = st.integers (min_value=100, max_value=999)
    typeSt = st.sampled_from (['Document', 'Stylesheet', 'Image', 'Media',
            'Font', 'Script', 'TextTrack', 'XHR', 'Fetch', 'EventSource',
            'WebSocket', 'Manifest', 'SignedExchange', 'Ping',
            'CSPViolationReport', 'Other'])
    return st.fixed_dictionaries ({
            'requestId': reqid,
            'timestamp': timestamp,
            'type': typeSt,
            'response': st.fixed_dictionaries ({
                'url': url,
                'requestHeaders': chromeHeaders (), # XXX: make this optional
                'headers': chromeHeaders (),
                'status': statusCodeSt,
                'statusText': asciiText,
                'mimeType': mimeTypeSt,
                'remoteIPAddress': remoteIpAddressSt,
                'protocol': protocolSt,
                })
            })
Exemplo n.º 57
0
def to_parameters(
    *,
    names: Strategy[str] = identifiers,
    kinds: Strategy[Parameter.Kind],
    has_default_flags: Strategy[bool] = strategies.booleans()
) -> Strategy[Parameter]:
    def normalize_mapping(mapping: Dict[str, Any]) -> Dict[str, Any]:
        if mapping['kind'] not in (Parameter.positionals_kinds
                                   | Parameter.keywords_kinds):
            return {**mapping, 'has_default': False}
        return mapping

    return (strategies.fixed_dictionaries(
        dict(name=names, kind=kinds, has_default=has_default_flags)).map(
            normalize_mapping).map(lambda mapping: Parameter(**mapping)))
Exemplo n.º 58
0
def introducer_configuration(node_pems=node_pems):
    return strategies.fixed_dictionaries({
        "port": port_number(),
        "node_pem": node_pems(),

        "introducer-swissnum": swissnum(),
        "log-gatherer-swissnum": swissnum(),
        "stats-gatherer-swissnum": swissnum(),
    }).map(
        _add_furl("introducer-swissnum", "introducer_furl")
    ).map(
        _add_furl("log-gatherer-swissnum", "log_gatherer_furl")
    ).map(
        _add_furl("stats-gatherer-swissnum", "stats_gatherer_furl")
    )
Exemplo n.º 59
0
def process_arguments_to_given(
    wrapped_test,
    arguments,
    kwargs,
    generator_arguments,
    generator_kwargs,
    argspec,
    test,
    settings,
):
    selfy = None
    arguments, kwargs = convert_positional_arguments(wrapped_test, arguments, kwargs)

    # If the test function is a method of some kind, the bound object
    # will be the first named argument if there are any, otherwise the
    # first vararg (if any).
    if argspec.args:
        selfy = kwargs.get(argspec.args[0])
    elif arguments:
        selfy = arguments[0]

    # Ensure that we don't mistake mocks for self here.
    # This can cause the mock to be used as the test runner.
    if is_mock(selfy):
        selfy = None

    test_runner = new_style_executor(selfy)

    arguments = tuple(arguments)

    # We use TupleStrategy over tuples() here to avoid polluting
    # st.STRATEGY_CACHE with references (see #493), and because this is
    # trivial anyway if the fixed_dictionaries strategy is cacheable.
    search_strategy = TupleStrategy(
        (
            st.just(arguments),
            st.fixed_dictionaries(generator_kwargs).map(
                lambda args: dict(args, **kwargs)
            ),
        )
    )

    if selfy is not None:
        search_strategy = WithRunner(search_strategy, selfy)

    search_strategy.validate()

    return arguments, kwargs, test_runner, search_strategy