Python hypothesis.strategies.just() Examples
The following are 30
code examples of hypothesis.strategies.just().
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.strategies
, or try the search function
.
Example #1
Source File: test_matching.py From xapi-profiles with Apache License 2.0 | 6 votes |
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 #2
Source File: space_test.py From bayesmark with Apache License 2.0 | 6 votes |
def test_joint_space_warp_fixed_vars(args): meta, X, _, fixed_vars = args # set X vals equal to fixed_vars for xx in X: for param in fixed_vars: xx[param] = fixed_vars[param] S = sp.JointSpace(meta) lower, upper = S.get_bounds().T X_w = S.warp(X) assert X_w.dtype == sp.WARPED_DTYPE # Test bounds lower, upper = S.get_bounds().T assert np.all(lower <= X_w) assert np.all(X_w <= upper) X2 = S.unwarp(X_w, fixed_vals=fixed_vars) # Make sure we get == not just close in unwarp for fixed vars for xx in X2: for param in fixed_vars: assert xx[param] == fixed_vars[param]
Example #3
Source File: xr_util_test.py From bayesmark with Apache License 2.0 | 6 votes |
def ds_vars_dims_mixed(): def build_it(vars_to_dims_): all_dims = list(set(sum((list(dd) for dd in vars_to_dims_.values()), []))) ds = fixed_datasets(vars_to_dims_) dims = subset_lists(all_dims) vars_ = sampled_from(list(vars_to_dims_.keys())) vars_dict = dictionaries(vars_, dims, dict_class=OrderedDict) vars_dict = vars_dict.map(OrderedDict.items).map(list) return tuples(ds, vars_dict, just(all_dims)) vars_to_dims_st = vars_to_dims_dicts(min_vars=0, min_dims=0) S = vars_to_dims_st.flatmap(build_it) return S
Example #4
Source File: generator.py From recordexpungPDX with MIT License | 6 votes |
def _build_charge_strategy( draw: Callable[[SearchStrategy], Any], charge_type: ChargeType, case: CaseSummary ) -> SearchStrategy[Charge]: if charge_type == DismissedCharge(): disposition_status = one_of( just(DispositionStatus.DISMISSED), just(DispositionStatus.NO_COMPLAINT), just(DispositionStatus.DIVERTED) ) else: disposition_status = one_of(just(DispositionStatus.CONVICTED), just(DispositionStatus.UNRECOGNIZED)) disposition_date = just(DateWithFuture(date=draw(dates(max_value=date(9000, 12, 31))))) disposition = builds(Disposition, status=disposition_status, date=disposition_date) arrest_date = just(DateWithFuture(date=draw(dates(max_value=date(9000, 12, 31))))) probation_revoked_date = one_of(none(), just(DateWithFuture(date=draw(dates(max_value=date(9000, 12, 31)))))) return draw( builds( Charge, charge_type=just(charge_type), case_number=just(case.case_number), disposition=disposition, date=arrest_date, probation_revoked=probation_revoked_date, ) )
Example #5
Source File: test_utils.py From MyGrad with MIT License | 6 votes |
def test_reduce_broadcast_keepdim(var_shape, data): """ example broadcasting: (2, 1, 4) -> (2, 5, 4)""" grad = data.draw( hnp.arrays( dtype=float, shape=broadcastable_shapes( shape=var_shape, min_dims=len(var_shape), max_dims=len(var_shape) ), elements=st.just(1.0), ), label="grad", ) reduced_grad = reduce_broadcast(grad=grad, var_shape=var_shape) assert reduced_grad.shape == tuple( i if i < j else j for i, j in zip(var_shape, grad.shape) ) assert (i == 1 for i, j in zip(var_shape, grad.shape) if i < j) sum_axes = tuple(n for n, (i, j) in enumerate(zip(var_shape, grad.shape)) if i != j) assert_allclose(actual=reduced_grad, desired=grad.sum(axis=sum_axes, keepdims=True))
Example #6
Source File: base.py From sidekick with MIT License | 6 votes |
def fcall(fn, args=None, kwargs=None): """ Call function with given positional and keyword args. """ if args == () or args is None: args = st.just(()) elif isinstance(args, (tuple, list)): args = st.tuples(*args) if kwargs == {} or kwargs is None: kwargs = st.just({}) elif isinstance(kwargs, dict): ks = list(kwargs.keys()) kwargs = st.builds(lambda *xs: dict(zip(ks, xs)), *kwargs.values()) return st.builds(lambda xs, kw: fn(*xs, **kw), args, kwargs)
Example #7
Source File: tree.py From sidekick with MIT License | 6 votes |
def trees(*args, max_depth=None, allow_attrs=True, **kwargs): """ Return random trees. """ attrs = st.just([]) kwargs["allow_attrs"] = allow_attrs if allow_attrs: keys = identifiers(allow_private=False, exclude=("children", "parent")) attr = st.tuples(keys, kwargs.get("attrs") or atoms()) attrs = st.lists(attr) fn = partial(shape_tree, max_depth) return st.builds(fn, attrs, st.lists(leaves(*args, **kwargs))) # # Utility functions #
Example #8
Source File: __init__.py From cattrs with MIT License | 6 votes |
def _create_hyp_class(attrs_and_strategy): """ A helper function for Hypothesis to generate attrs classes. The result is a tuple: an attrs class, and a tuple of values to instantiate it. """ def key(t): return t[0].default is not NOTHING attrs_and_strat = sorted(attrs_and_strategy, key=key) attrs = [a[0] for a in attrs_and_strat] for i, a in enumerate(attrs): a.counter = i vals = tuple((a[1]) for a in attrs_and_strat) return st.tuples( st.just( make_class("HypClass", OrderedDict(zip(gen_attr_names(), attrs))) ), st.tuples(*vals), )
Example #9
Source File: test_browser.py From crocoite with MIT License | 6 votes |
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, }) })
Example #10
Source File: test_persistence.py From flocker with Apache License 2.0 | 6 votes |
def _build_node(applications): # All the manifestations in `applications`. app_manifestations = set( app.volume.manifestation for app in applications if app.volume ) # A set that contains all of those, plus an arbitrary set of # manifestations. dataset_ids = frozenset( app.volume.manifestation.dataset_id for app in applications if app.volume ) manifestations = ( st.sets(MANIFESTATIONS.filter( lambda m: m.dataset_id not in dataset_ids)) .map(pset) .map(lambda ms: ms.union(app_manifestations)) .map(lambda ms: dict((m.dataset.dataset_id, m) for m in ms))) return st.builds( Node, uuid=st.uuids(), applications=st.just({a.name: a for a in applications}), manifestations=manifestations)
Example #11
Source File: __init__.py From cattrs with MIT License | 6 votes |
def _create_hyp_nested_strategy(simple_class_strategy): """ Create a recursive attrs class. Given a strategy for building (simpler) classes, create and return a strategy for building classes that have as an attribute: * just the simpler class * a list of simpler classes * a dict mapping the string "cls" to a simpler class. """ # A strategy producing tuples of the form ([list of attributes], <given # class strategy>). attrs_and_classes = st.tuples( lists_of_attrs(defaults=True), simple_class_strategy ) return ( attrs_and_classes.flatmap(just_class) | attrs_and_classes.flatmap(just_class_with_type) | attrs_and_classes.flatmap(list_of_class) | attrs_and_classes.flatmap(list_of_class_with_type) | attrs_and_classes.flatmap(dict_of_class) )
Example #12
Source File: _from_schema.py From hypothesis-jsonschema with Mozilla Public License 2.0 | 6 votes |
def regex_patterns(draw: Any) -> str: """Return a recursive strategy for simple regular expression patterns.""" fragments = st.one_of( st.just("."), st.from_regex(r"\[\^?[A-Za-z0-9]+\]"), REGEX_PATTERNS.map("{}+".format), REGEX_PATTERNS.map("{}?".format), REGEX_PATTERNS.map("{}*".format), ) result = draw(st.lists(fragments, min_size=1, max_size=3).map("".join)) assert isinstance(result, str) try: re.compile(result) except re.error: assume(False) return result
Example #13
Source File: test_float.py From segpy with GNU Affero General Public License v3.0 | 6 votes |
def ibm_compatible_floats(draw, min_value=None, max_value=None): if min_value is None: min_value = MIN_IBM_FLOAT if max_value is None: max_value = MAX_IBM_FLOAT truncated_min_f = max(min_value, MIN_IBM_FLOAT) truncated_max_f = min(max_value, MAX_IBM_FLOAT) strategies = [] if truncated_min_f <= LARGEST_NEGATIVE_NORMAL_IBM_FLOAT <= truncated_max_f: strategies.append(floats(truncated_min_f, LARGEST_NEGATIVE_NORMAL_IBM_FLOAT)) if truncated_min_f <= SMALLEST_POSITIVE_NORMAL_IBM_FLOAT <= truncated_max_f: strategies.append(floats(SMALLEST_POSITIVE_NORMAL_IBM_FLOAT, truncated_max_f)) if truncated_min_f <= 0 <= truncated_max_f: strategies.append(just(0.0)) if len(strategies) == 0: strategies.append(floats(truncated_min_f, truncated_max_f)) ibm = draw(one_of(*strategies)) return ibm
Example #14
Source File: space_test.py From bayesmark with Apache License 2.0 | 5 votes |
def test_encode_broadcast_float(): broadcast_tester( sp.encode, "(),(n),(),(),()->(n)", otype=float, excluded=(1, 2, 3, 4), dtype=[np.int_, CAT_DTYPE, np.bool_, object, np.bool_], elements=[integers(0, INT_MAX), from_dtype(np.dtype(CAT_DTYPE)), booleans(), just("float"), booleans()], unique=[False, True, False, False, False], min_side={"n": 1}, map_=encoder_gen, )
Example #15
Source File: __init__.py From cattrs with MIT License | 5 votes |
def dict_of_class(tup): nested_cl = tup[1][0] default = attr.Factory(lambda: {"cls": nested_cl()}) combined_attrs = list(tup[0]) combined_attrs.append( (attr.ib(default=default), st.just({"cls": nested_cl()})) ) return _create_hyp_class(combined_attrs)
Example #16
Source File: gen_schemas.py From hypothesis-jsonschema with Mozilla Public License 2.0 | 5 votes |
def _json_schemata(draw: Any, recur: bool = True) -> Any: # Current version of jsonschema does not support boolean schemata, # but 3.0 will. See https://github.com/Julian/jsonschema/issues/337 options = [ st.builds(dict), st.just({"type": "null"}), st.just({"type": "boolean"}), gen_number("integer"), gen_number("number"), gen_string(), st.builds(dict, const=JSON_STRATEGY), gen_enum(), st.booleans(), ] if recur: options += [ gen_array(), gen_object(), # Conditional subschemata gen_if_then_else(), json_schemata().map(lambda v: assume(v and v is not True) and {"not": v}), st.builds(dict, anyOf=st.lists(json_schemata(), min_size=1)), st.builds(dict, oneOf=st.lists(json_schemata(), min_size=1, max_size=2)), st.builds(dict, allOf=st.lists(json_schemata(), min_size=1, max_size=2)), ] return draw(st.one_of(options))
Example #17
Source File: _from_schema.py From hypothesis-jsonschema with Mozilla Public License 2.0 | 5 votes |
def string_schema(schema: dict) -> st.SearchStrategy[str]: """Handle schemata for strings.""" # also https://json-schema.org/latest/json-schema-validation.html#rfc.section.7 min_size = schema.get("minLength", 0) max_size = schema.get("maxLength") strategy = st.text(min_size=min_size, max_size=max_size) if schema.get("format") in STRING_FORMATS: # Unknown "format" specifiers should be ignored for validation. # See https://json-schema.org/latest/json-schema-validation.html#format strategy = STRING_FORMATS[schema["format"]] if "pattern" in schema: # This isn't really supported, but we'll do our best. strategy = strategy.filter( lambda s: re.search(schema["pattern"], string=s) is not None ) elif "pattern" in schema: try: re.compile(schema["pattern"]) strategy = st.from_regex(schema["pattern"]) except re.error: # Patterns that are invalid in Python, or just malformed return st.nothing() # If we have size bounds but we're generating strings from a regex or pattern, # apply a filter to ensure our size bounds are respected. if ("format" in schema or "pattern" in schema) and ( min_size != 0 or max_size is not None ): max_size = math.inf if max_size is None else max_size strategy = strategy.filter(lambda s: min_size <= len(s) <= max_size) return strategy
Example #18
Source File: tester.py From hypothesis-auto with MIT License | 5 votes |
def auto_parameters( auto_function_: Callable, *args, auto_limit_: int = 50, **kwargs ) -> Generator[Parameters, None, None]: """Generates parameters from the given callable up to the specified limit (`auto_limit_` parameter). By default auto_parameters uses type annotations to automatically decide on strategies via the hypothesis builds strategy. You can override individual strategies by passing them in under the corresponding `*arg` or `**kwarg` OR you can pass in specific values that must be used for certain parameters while letting others be auto generated. All `*arg` and `**kwargs` are automatically passed along to `hypothesis.strategies.builds` to enable this. Non strategies are automatically converted to strategies using `hypothesis.strategies.just`. Except for the following option: - *auto_limit_*: Number of strategies combinations to run the given function against. """ strategy_args = [arg if isinstance(arg, SearchStrategy) else just(arg) for arg in args] strategy_kwargs = { name: value if isinstance(value, SearchStrategy) else just(value) for name, value in kwargs.items() } def pass_along_variables(*args, **kwargs): return Parameters(args=args, kwargs=kwargs) pass_along_variables.__signature__ = signature(auto_function_) # type: ignore pass_along_variables.__annotations__ = getattr(auto_function_, "__annotations__", {}) strategy = builds(pass_along_variables, *strategy_args, **strategy_kwargs) for _ in range(auto_limit_): yield strategy.example()
Example #19
Source File: tester.py From hypothesis-auto with MIT License | 5 votes |
def auto_test_cases( auto_function_: Callable, *args, auto_allow_exceptions_: Union[Tuple[BaseException], Tuple] = (), auto_limit_: int = 50, auto_verify_: Optional[Callable[[Scenario], Any]] = None, **kwargs ) -> Generator[TestCase, None, None]: """Generates test cases from the given callable up to the specified limit (`auto_limit_` parameter). By default auto_test_cases uses type annotations to automatically decide on strategies via the hypothesis builds strategy. You can override individual strategies by passing them in under the corresponding `*arg` or `**kwarg` OR you can pass in specific values that must be used for certain parameters while letting others be auto generated. All `*arg` and `**kwargs` are automatically passed along to `hypothesis.strategies.builds` to enable this. Non strategies are automatically converted to strategies using `hypothesis.strategies.just`. Except for the following options: - *auto_allow_exceptions_*: A tuple of exceptions that are acceptable for the function to raise and will no be considered a test error. - *auto_limit_*: Number of strategies combinations to run the given function against. - *auto_verify_*: An optional callback function that will be called to allow custom verification of the functions return value. The callback function should raise an AssertionError if the return value does not match expectations. """ test_function = _test_function( auto_function_, auto_verify_=auto_verify_, auto_allow_exceptions_=auto_allow_exceptions_ ) for parameters in auto_parameters(auto_function_, *args, auto_limit_=auto_limit_, **kwargs): yield TestCase(parameters=parameters, test_function=test_function)
Example #20
Source File: tester.py From hypothesis-auto with MIT License | 5 votes |
def auto_test( auto_function_: Callable, *args, auto_allow_exceptions_: Union[Tuple[BaseException], Tuple] = (), auto_runs_: int = 50, auto_verify_: Optional[Callable[[Scenario], Any]] = None, **kwargs ) -> None: """A simple utility function for hypothesis that enables fully automatic testing for a type hinted callable, including return type verification. By default auto_test uses type annotations to automatically decide on strategies via the hypothesis builds strategy. You can override individual strategies by passing them in under the corresponding `*arg` or `**kwarg` OR you can pass in specific values that must be used for certain parameters while letting others be auto generated. All `*arg` and `**kwargs` are automatically passed along to `hypothesis.strategies.builds` to enable this. Non strategies are automatically converted to strategies using `hypothesis.strategies.just`. Except for the following options: - *auto_allow_exceptions_*: A tuple of exceptions that are acceptable for the function to raise and will no be considered a test error. - *auto_runs_*: Number of strategies combinations to run the given function against. - *auto_verify_*: An optional callback function that will be called to allow custom verification of the functions return value. The callback function should raise an AssertionError if the return value does not match expectations. """ for test_case in auto_test_cases( auto_function_, *args, auto_allow_exceptions_=auto_allow_exceptions_, auto_limit_=auto_runs_, auto_verify_=auto_verify_, **kwargs ): test_case()
Example #21
Source File: _from_schema.py From hypothesis-jsonschema with Mozilla Public License 2.0 | 5 votes |
def relative_json_pointers() -> st.SearchStrategy[str]: """Return a strategy for strings in relative-json-pointer format.""" return st.builds( operator.add, st.from_regex(r"0|[1-9][0-9]*", fullmatch=True), st.just("#") | json_pointers(), ) # Via the `webcolors` package, to match the logic `jsonschema` # uses to check it's (non-standard?) "color" format.
Example #22
Source File: generator.py From recordexpungPDX with MIT License | 5 votes |
def _build_case_strategy(draw: Callable[[SearchStrategy], Any], min_charges_size=0) -> Case: case_summary = draw(builds(CaseSummary, date=just(DateWithFuture(date=draw(dates()))))) charge_classes = get_charge_classes() charge_strategy_choices = list( map(lambda charge_class: _build_charge_strategy(charge_class(), case_summary), charge_classes) ) charge_strategy = one_of(charge_strategy_choices) charges = draw(lists(charge_strategy, min_charges_size)) return Case(case_summary, charges=tuple(charges))
Example #23
Source File: hashable_strategies.py From py-ssz with MIT License | 5 votes |
def boolean_sedes_and_values_st(): return st.just((boolean, bool_value_st()))
Example #24
Source File: hashable_strategies.py From py-ssz with MIT License | 5 votes |
def bitlist_sedes_and_values_st(draw): max_size = draw( st.one_of( st.integers(1, 10), st.just(300), # choose at least one sample exceeding one chunk ) ) return Bitlist(max_size), bitlist_value_st(max_size)
Example #25
Source File: hashable_strategies.py From py-ssz with MIT License | 5 votes |
def bitvector_sedes_and_values_st(draw): size = draw( st.one_of( st.integers(1, 10), st.just(300), # choose at least one sample exceeding one chunk ) ) return Bitvector(size), bitvector_value_st(size)
Example #26
Source File: _from_schema.py From hypothesis-jsonschema with Mozilla Public License 2.0 | 5 votes |
def rfc3339(name: str) -> st.SearchStrategy[str]: """Get a strategy for date or time strings in the given RFC3339 format. See https://tools.ietf.org/html/rfc3339#section-5.6 """ # Hmm, https://github.com/HypothesisWorks/hypothesis/issues/170 # would make this a lot easier... assert name in RFC3339_FORMATS def zfill(width: int) -> Callable[[int], str]: return lambda v: str(v).zfill(width) simple = { "date-fullyear": st.integers(0, 9999).map(zfill(4)), "date-month": st.integers(1, 12).map(zfill(2)), "date-mday": st.integers(1, 28).map(zfill(2)), # incomplete but valid "time-hour": st.integers(0, 23).map(zfill(2)), "time-minute": st.integers(0, 59).map(zfill(2)), "time-second": st.integers(0, 59).map(zfill(2)), # ignore negative leap seconds "time-secfrac": st.from_regex(r"\.[0-9]+"), } if name in simple: return simple[name] if name == "time-numoffset": return st.tuples( st.sampled_from(["+", "-"]), rfc3339("time-hour"), rfc3339("time-minute") ).map("%s%s:%s".__mod__) if name == "time-offset": return st.one_of(st.just("Z"), rfc3339("time-numoffset")) if name == "partial-time": return st.times().map(str) if name == "date" or name == "full-date": return st.dates().map(str) if name == "time" or name == "full-time": return st.tuples(rfc3339("partial-time"), rfc3339("time-offset")).map("".join) assert name == "date-time" return st.tuples(rfc3339("full-date"), rfc3339("full-time")).map("T".join)
Example #27
Source File: strategies.py From requirementslib with MIT License | 5 votes |
def repo_url_strategy(): def url_encode(s): return "".join(c if c in URL_SAFE_CHARACTERS else "%%%02X" % ord(c) for c in s) paths = st.lists(st.text(string.printable).map(url_encode)).map("/".join) ports = st.integers(min_value=0, max_value=65535).map(":{}".format) fragments = ( st.text(alphabet="abcdefghijklmnopqrstuvwxyz0123456789_-.") .map(url_encode) .map("#egg={}".format) .map(lambda x: "" if x == "#egg=" else x) ) refs = ( st.text(alphabet="abcdefghijklmnopqrstuvwxyz0123456789_-") .map(url_encode) .map("@{}".format) .map(lambda x: "" if x == "@" else x) ) scheme = ( st.sampled_from(vcs_schemes) .filter(lambda x: "+" in x) .map("{}://".format) .map(lambda x: x.replace("file://", "file:///")) ) auth = ( auth_strings() .map("{}@".format) .map(lambda x: "" if x == "@" else x) .map(lambda x: x.replace(":@", "@") if x.endswith(":@") else x) ) domain = domains().map(lambda x: x.lower()) return st.builds( "{}{}{}{}{}{}{}".format, scheme, auth, domain, st.just("|") | ports, paths, refs, fragments, ).map(lambda x: x.replace("|", ":") if "git+git@" in x else x.replace("|", "/"))
Example #28
Source File: __init__.py From cattrs with MIT License | 5 votes |
def frozen_sets_of_primitives(draw): """A strategy that generates frozen sets of primitives.""" prim_strat, t = draw(primitive_strategies) set_t = draw(st.just(Set) | st.just(Set[t])) return frozenset(draw(st.sets(prim_strat))), set_t
Example #29
Source File: test_typeclass_laws.py From python-lenses with GNU General Public License v3.0 | 5 votes |
def objects(): return strat.just(object())
Example #30
Source File: __init__.py From cattrs with MIT License | 5 votes |
def bare_attrs(draw, defaults=None): """ Generate a tuple of an attribute and a strategy that yields values appropriate for that attribute. """ default = NOTHING if defaults is True or (defaults is None and draw(st.booleans())): default = None return (attr.ib(default=default), st.just(None))