def test_custom_strategies(): register_string_format( "even_4_digits", strategies.from_regex(r"\A[0-9]{4}\Z").filter( lambda x: int(x) % 2 == 0)) endpoint = make_endpoint( **{ "query": { "required": ["id"], "type": "object", "additionalProperties": False, "properties": { "id": { "type": "string", "format": "even_4_digits" } }, } }) result = strategies.builds( Case, path=strategies.just(endpoint.path), method=strategies.just(endpoint.method), query=from_schema(endpoint.query), ).example() assert len(result.query["id"]) == 4 assert int(result.query["id"]) % 2 == 0
def test_custom_strategies(): register_string_format("even_4_digits", strategies.from_regex(r"\A[0-9]{4}\Z").filter(lambda x: int(x) % 2 == 0)) endpoint = make_endpoint( query={ "required": ["id"], "type": "object", "additionalProperties": False, "properties": {"id": {"type": "string", "format": "even_4_digits"}}, } ) result = get_case_strategy(endpoint).example() assert len(result.query["id"]) == 4 assert int(result.query["id"]) % 2 == 0
def test_custom_strategies(swagger_20): register_string_format("even_4_digits", st.from_regex(r"\A[0-9]{4}\Z").filter(lambda x: int(x) % 2 == 0)) endpoint = make_endpoint( swagger_20, query=ParameterSet( [ OpenAPI20Parameter( {"name": "id", "in": "query", "required": True, "type": "string", "format": "even_4_digits"} ) ] ), ) result = get_case_strategy(endpoint).example() assert len(result.query["id"]) == 4 assert int(result.query["id"]) % 2 == 0
def test_invalid_custom_strategy(values, error): with pytest.raises(TypeError) as exc: register_string_format(*values) assert error in str(exc.value)
from datetime import timedelta from hypothesis import strategies as st import schemathesis @st.composite def fullname(draw): """Custom strategy for full names.""" first = draw(st.sampled_from(["jonh", "jane"])) last = draw(st.just("doe")) return f"{first} {last}" schemathesis.register_string_format("fullname", fullname()) @schemathesis.hooks.register def before_generate_body(context, strategy): """Modification over the default strategy for payload generation.""" return strategy.filter(lambda x: x.get("id", 10001) > 10000) @schemathesis.register_check def not_so_slow(response, case): """Custom response check.""" assert response.elapsed < timedelta(milliseconds=100), "Response is slow!" @schemathesis.register_target