Resource is Merit’s dependency injection system that provides reusable components to merit functions. It follows pytest’s fixture pattern, matching function parameters by name to automatically inject dependencies.
Using @merit.resource enables:
- Injecting dependencies into merit functions without explicit instantiation
- Sharing expensive setup across multiple merits (database connections, API clients)
- Automatic teardown and cleanup with generator syntax
- Scoping lifecycles at case, suite, or session level
- Stacking resources to build complex dependency hierarchies
Basic Usage
The most common pattern is to define a resource function and inject it into your merit tests by parameter name.api_client parameter, calls the resource function, and injects the result. No explicit wiring needed.
Generator Pattern for Setup and Teardown
Resources can use generator syntax to define setup and teardown logic, similar to pytest fixtures withyield.
yield runs automatically after the merit completes, ensuring cleanup even if the merit fails.
Async Resources
Resources support async functions and async generators for asynchronous setup/teardown.Scopes: Case, Suite, Session
Resources can be scoped to control their lifecycle and determine how instances are shared across merits."case": New instance per parametrized merit case (default)"suite": One instance per merit file/module"session": One instance for entire merit run
Stacking Resources: Dependency Injection
Resources can depend on other resources by declaring them as parameters. This enables building complex dependency graphs and composing reusable components.config is created once per session, http_client once per suite, and authenticated_client fresh for each merit case.
Lifecycle Hooks
Resources support three optional hooks for advanced control:- on_resolve: Called once when resource is first created (after factory runs, before caching)
- on_injection: Called every time the resource is injected into a merit (even from cache)
- on_teardown: Called after generator teardown code runs (post-yield)