def _( arg=each("invalid-scope", 123), expected_cause_ex_type=each(KeyError, AttributeError), ): with raises(FixtureError) as fixture_error: Scope.from_str(arg) assert type(fixture_error.raised.__cause__) is expected_cause_ex_type
def _(output_style=each("dots-global", "dots-module")): runner = CliRunner() result = runner.invoke(run, [ "test", "--progress-style", "bar", "--test-output-style", output_style ]) assert result.exit_code == 2
def _(data=repeats, threshold=each(15, 20, 25)): component = find_component_slow(data, threshold) components = np.zeros(len(data), np.int16) find_component(data, components, label=1, threshold=threshold) assert set(np.nonzero(components)[0]) == component
def _( func=each( assert_equal, assert_not_equal, assert_in, assert_not_in, assert_less_than, assert_less_than_equal_to, assert_greater_than, assert_greater_than_equal_to, ), lhs=each(1, 1, "a", "a", 2, 2, 1, 1), rhs=each(2, 1, "b", "a", 1, 1, 2, 2), ): with raises(TestFailure): func(lhs, rhs, "")
def _(exit_code=each(0, 1)): @fixture def exits(): sys.exit(exit_code) t = Test(fn=lambda exits=exits: None, module_name="foo") with raises(FixtureError): t.resolver.resolve_args(FixtureCache())
def _( func=each( assert_equal, assert_not_equal, assert_in, assert_not_in, assert_is, assert_is_not, assert_less_than, assert_less_than_equal_to, assert_less_than_equal_to, assert_greater_than, assert_greater_than_equal_to, assert_greater_than_equal_to, ), lhs=each(1, 1, "a", "a", ..., True, 1, 1, 1, 2, 2, 1), rhs=each(1, 2, "a", "b", ..., None, 2, 2, 1, 1, 1, 1), ): assert func(lhs, rhs, "") is None
async def _( internalapi_graphql_client=internalapi_graphql_client, db=db, status=each(SubscriptionStatus.CANCELED, SubscriptionStatus.PENDING), ): await SubscriptionFactory(user_id=1, status=status) internalapi_graphql_client.force_service_login( issuer="pycon-backend", audience="association-backend") query = """query($id: ID!) { userIdIsMember(id: $id) }""" response = await internalapi_graphql_client.query(query, variables={"id": "1"}) assert not response.errors assert response.data["userIdIsMember"] is False
async def _(graphql_client=graphql_client, email=each("", "invalid.email"), db=db): query = """mutation($input: RegisterInput!) { register(input: $input) { __typename ... on RegisterValidationError { errors { password { message type } email { message type } } } } } """ response = await graphql_client.query( query, variables={"input": { "email": email, "password": "******" }}) assert not response.errors, response.errors assert response.data["register"] == { "__typename": "RegisterValidationError", "errors": { "email": [{ "message": "value is not a valid email address", "type": "value_error.email", }], "password": None, }, }
async def _(graphql_client=graphql_client, password=each("", "short"), db=db): query = """mutation($input: RegisterInput!) { register(input: $input) { __typename ... on RegisterValidationError { errors { password { message type } email { message type } } } } } """ response = await graphql_client.query( query, variables={"input": { "email": "*****@*****.**", "password": password }}) assert not response.errors, response.errors assert response.data["register"] == { "__typename": "RegisterValidationError", "errors": { "password": [{ "message": "ensure this value has at least 8 characters", "type": "value_error.any_str.min_length", }], "email": None, }, }
def _(x=each(*range(500))): assert False
def _(x=each(*range(500))): pass
@fixture @using(api=api) def template_view(api: Api): @api.route("/template") class TemplateView: async def on_post(_, req, resp): name = (await req.content).decode("utf8") await resp.load_template("test.html", name=name) return TemplateView @test("Response can render Jinja2 template") @using(api=api, view=template_view, name=each(*template_names)) async def _(api: Api, view: type[RequestHandlerProtocol], name: str): path = api.url_for(view) async with api.client() as client: response = await client.post(path, content=name.encode("utf8")) assert response.status_code == HTTPStatus.OK assert escape(name) in response.text @fixture @using(api=api) def goal_view(api: Api): @api.route("/goal") class Goal: async def on_get(self, req, resp): resp.set_status(418)
def _( scope=each(Scope.Test, Scope.Module, Scope.Global), string=each("test", "module", "global"), ): assert Scope.from_str(string) == scope
from inari.collectors import FunctionCollector from ward import each, test, using from .fixtures import _func_expected_doc, _temp_dir, target_function @test("`doc_str` should return correct document.") @using(out_dir=_temp_dir, result=each(_func_expected_doc)) def _(out_dir: str, result: str) -> None: collector = FunctionCollector(target_function, {}, out_dir) assert collector.doc_str() == result
from inspect import cleandoc from inari.collectors import ClassCollector from ward import each, test, using from .fixtures import TargetClass, _temp_dir @test("`doc_str` should return correct document.") @using(cls=each(TargetClass), out_dir=_temp_dir) def _(cls: type, out_dir: str) -> None: collector = ClassCollector(cls, out_dir, {}) assert collector.doc_str() == cleandoc(getattr(cls, "_expected_doc"))
def foo( a=each(dummy_fixture, "foo", dummy_fixture, "fourth"), b=each("bar", dummy_fixture, dummy_fixture, "fourth"), ): pass
def _(arg=each("x", 1, True, ["a", "b"]), rv=each(["x"], [1], [True], ["a", "b"])): assert as_list(arg) == rv
import pathlib from os.path import isfile from types import ModuleType from inari.collectors import ModuleCollector from ward import each, test, using from . import blank_module from . import fixtures as target_module @test("`doc_str` should return correct document.") @using( module=each(target_module, blank_module), result=each(target_module._mod_expected_docs, "# Module tests.collectors.blank_module"), out_dir=target_module._temp_dir, ) def _(module: ModuleType, result: str, out_dir: str) -> None: collector = ModuleCollector(module, out_dir, {}) assert collector.doc_str() == result @test("`write` should write docs on expected paths.") @using( module=each(target_module, blank_module), out_dir=target_module._temp_dir, out_name=each("fixtures-py.md", "blank_module/index.md"), ) def _(module: ModuleType, out_dir: str, out_name: str) -> None: collector = ModuleCollector(module, out_dir, {})
("/start/allowed/", HTTPStatus.OK), ("/start/patterns/here", HTTPStatus.OK), ("/start/patterns/here/", HTTPStatus.OK), ("/start/foo", HTTPStatus.OK), ("/start/foo/", HTTPStatus.OK), ("/start/bar/params", HTTPStatus.OK), ("/start/bar/params/", HTTPStatus.OK), ("/start/notfound", HTTPStatus.NOT_FOUND), ("/start/notfound/", HTTPStatus.NOT_FOUND), ] @test( "A blueprint returns same response against paths with or without a trailing slash" ) @using(api=api, bp=routes, path_code=each(*clone_paths)) async def _(api: Api, bp: Blueprint, path_code: tuple[str, int]): api.routing = "clone" api.add_blueprint("/", bp) api.add_blueprint("start", bp) async with api.client() as client: path, code = path_code response = await client.get(path, allow_redirects=False) assert response.status_code == code strict_paths = [ ("/", HTTPStatus.OK), ("/allowed", HTTPStatus.OK), ("/allowed/", HTTPStatus.NOT_FOUND), ("/patterns/here", HTTPStatus.NOT_FOUND),
@api.route("/{path}") class ParamView: async def on_get(self, req, resp): params = cast(Params, use_params()) p = dict(**req.queries) path = params["path"] assert queries[path] == p assert req.full_url.startswith(f"http://www.example.com/{path}") return resp return ParamView @test("Url params and qs values `{query}` are passed to the view") @using(api=api, view=param_view, query=each(*queries.items())) async def _(api: Api, view: type[RequestHandlerProtocol], query: tuple[str, dict]): path = api.url_for(view, {"path": query[0]}) async with api.client() as client: response = await client.get(path, queries=query[1]) assert response.status_code == HTTPStatus.OK @fixture @using(api=api) def client_info(api: Api): @api.route("/info") class ClientInfo: async def on_get(_, req, resp): assert req.client.host == "127.0.0.1" assert req.client.port == 123
def _(not_fixture=each("foo", 5, is_fixture, Fixture)): assert not is_fixture(not_fixture)
"- `str`: Return type.\n", ) no_description = Fixtures( raw_description="* no_description(`str`)", attributes="", result="- **no_description** (`str`)", ) @test( "Description `` {raw_description} `` with `` {attributes} `` should be modified " + "into `` {result} `` .") @using( raw_description=each( simple.raw_description, attr_and_emphasize.raw_description, multiline.raw_description, no_description.raw_description, ), attributes=each( simple.attributes, attr_and_emphasize.attributes, multiline.attributes, no_description.attributes, ), result=each( simple.result, attr_and_emphasize.result, multiline.result, no_description.result, ), )
def _(method=each("get", "delete", "patch")): client = TestClient(app) response = getattr(client, method)("/pretix-webhook") assert response.status_code == 405
def _(data=repeats, batch_size=each(1, 2, 3)): degrees = degree_by_similarity(data) batched_degrees = degree_by_similarity(data, progress=True, batch_size=batch_size) assert np.all(batched_degrees == degrees)
def _(data=repeats, threshold=each(15, 20, 25)): data = data[:10] components_slow = find_components_slow(data, threshold) components = find_components(data, threshold) assert (components == components_slow).all()
api.on_start(start) return start @fixture @using(api=api) def stop_async(api: Api): stop = AsyncMock() stop.__name__ = "stop_async" api.on_stop(stop) return stop @test("`{store.__name__}` lifespan methods are called once") @using(api=api, store=each(store_sync, store_async)) async def _(api: Api, store: type[AnyComponentProtocol]): async with api.client(): store_instance = use_component(store, api=api) assert isinstance(store_instance, store) store_instance._startup.assert_called_once() store_instance._shutdown.assert_not_called() store_instance._shutdown.assert_called_once() @test( "Lifespan function `{before.__name__}` and `{after.__name__}` are called once" ) @using( api=api,
def _(opt=each("exclude")): file_config = {opt: ["a", "b", "c"]} cli_config = {opt: ["a"]} assert apply_multi_defaults(file_config, cli_config) == {"path": ["."]}
link_to="/inari/foo/baz", result="baz") link_self = Fixtures(page="/inari/foo/bar", link_to="/inari/foo/bar", result="") another_dir = Fixtures(page="/inari/foo/bar", link_to="/inari/baz", result="../baz") another_dir_child = Fixtures(page="/inari/foo/bar", link_to="/inari/baz/spam", result="../baz/spam") @test("Relative link from `{page}` to `{link_to}` should be `{result}` .") @using( page=each(current_dir.page, link_self.page, another_dir.page, another_dir_child.page), link_to=each( current_dir.link_to, link_self.link_to, another_dir.link_to, another_dir_child.link_to, ), result=each( current_dir.result, link_self.result, another_dir.result, another_dir_child.result, ), ) def _(page: str, link_to: str, result: str) -> None: assert _path.get_relative_path(page, link_to) == result