A proc macro to ease development using Inversion of Control patterns in Rust.
entrait
is used to generate a trait from the definition of a regular function.
The main use case for this is that other functions may depend upon the trait instead of the concrete implementation, enabling better test isolation.
The macro looks like this:
```rust
fn my_function
which generates the trait MyFunction
:
rust
trait MyFunction {
fn my_function(&self);
}
my_function
's first and only parameter is deps
which is generic over some unknown type D
.
This would correspond to the self
parameter in the trait.
But what is this type supposed to be? The trait gets automatically implemented for Impl<T>
:
```rust use implementation::Impl; struct App;
fn myfunction
let app = Impl::new(App); app.my_function(); ```
The advantage of this pattern comes into play when a function declares its dependencies, as trait bounds:
```rust
fn foo(deps: &impl Bar) { deps.bar(); }
fn bar
The functions may take any number of parameters, but the first one is always considered specially as the "dependency parameter".
Functions may also be non-generic, depending directly on the App:
```rust use implementation::Impl;
struct App { something: SomeType }; type SomeType = u32;
fn generic(deps: &impl Concrete) -> SomeType { deps.concrete() }
fn concrete(app: &App) -> SomeType { app.something }
let app = Impl::new(App { something: 42 }); assert_eq!(42, app.generic()); ```
These kinds of functions may be considered "leaves" of a dependency tree.
The entrait
crate is a building block of a design pattern - the entrait pattern.
The entrait pattern is simply a convenient way to achieve unit testing of business logic.
Entrait is not intended for achieving polymorphism. If you want that, you should instead hand-write a trait.
Entrait should only be used to define an abstract computation that has a single implementation in realase mode, but is mockable in test mode.
entrait
does not implement Dependency Injection (DI). DI is a strictly object-oriented concept that will often look awkward in Rust.
The author thinks of DI as the "reification of code modules":
In a DI-enabled programming environment, code modules are grouped together as objects and other modules may depend upon the interface of such an object by receiving some instance that implements it.
When this pattern is applied successively, one ends up with an in-memory dependency graph of high-level modules.
entrait
tries to turn this around by saying that the primary abstraction that is depended upon is a set of functions, not a set of code modules.
An architectural consequence is that one ends up with one ubiquitous type that represents a running application that implements all these function abstraction traits. But the point is that this is all loosely coupled: Most function definitions themselves do not refer to this god-like type, they only depend upon traits.
by default, entrait generates a trait that is module-private (no visibility keyword). To change this, just put a visibility specifier before the trait name:
```rust use entrait::*;
fn foo
async
supportSince Rust at the time of writing does not natively support async methods in traits, you may opt in to having #[async_trait]
generated for your trait:
```rust
async fn foo
This is designed to be forwards compatible with real async fn in traits.
When that day comes, you should be able to just remove the
async_trait=true` to get a proper zero-cost future.
async
inversion of control - preview modeEntrait has experimental support for zero-cost futures. A nightly Rust compiler is needed for this feature.
The entrait feature is called associated_future
, and depends on generic_associated_types
and type_alias_impl_trait
.
This feature generates an associated future inside the trait, and the implementations use impl Trait
syntax to infer
the resulting type of the future:
```rust
use entrait::unimock::*;
async fn foo
fn
-targeting macros, and no_deps
Some macros are used to transform the body of a function, or generate a body from scratch.
For example, we can use feignhttp
to generate an HTTP client. Entrait will try as best as it
can to co-exist with macros like these. Since entrait
is a higher-level macro that does not touch fn bodies (it does not even try to parse them),
entrait should be processed after, which means it should be placed before lower level macros. Example:
```rust
async fn fetch_thing(#[path] param: String) -> feignhttp::Result
Here we had to use the no_deps
entrait option.
This is used to tell entrait that the function does not have a deps
parameter as its first input.
Instead, all the function's inputs get promoted to the generated trait method.
Entrait works best together with unimock, as these two crates have been designed from the start with each other in mind.
Unimock exports a single mock struct which can be passed in as parameter to every function that accept a deps
parameter
(given that entrait is used with unimock support everywhere).
To enable mocking of entraited functions, they get reified and defined as a type called Fn
inside a module with the same identifier as the function: entraited_function::Fn
.
Unimock support is enabled by importing entrait from the path entrait::unimock::*
.
```rust use entrait::unimock::; use unimock::;
fn foo
fn bar
fn my_func(deps: &(impl Foo + Bar)) -> i32 { deps.foo() + deps.bar() }
let mockeddeps = mock([ foo::Fn.eachcall(matching!()).returns(40).inanyorder(), bar::Fn.eachcall(matching!()).returns(2).inany_order(), ]);
asserteq!(42, myfunc(&mocked_deps)); ```
Entrait with unimock supports un-mocking. This means that the test environment can be partially mocked!
```rust use entrait::unimock::; use unimock::; use std::any::Any;
fn sayhello(deps: &impl FetchPlanetName, planetid: u32) -> Result
fn fetchplanetname(deps: &impl FetchPlanet, planetid: u32) -> Result
pub struct Planet { name: String }
fn fetchplanet(deps: &impl Any, planetid: u32) -> Result let hellostring = sayhello(
&spy([
fetchplanet::Fn
.eachcall(matching!())
.answers(|| Ok(Planet {
name: "World".tostring(),
}))
.inany_order(),
]),
123456,
).unwrap(); asserteq!("Hello World!", hellostring);
``` If you instead wish to use a more established mocking crate, there is also support for mockall.
Note that mockall has some limitations.
Multiple trait bounds are not supported, and deep tests will not work.
Also, mockall tends to generate a lot of code, often an order of magnitude more than unimock. Just import entrait from ```rust
use entrait::mockall::*; fn foo fn my_func(deps: &impl Foo) -> u32 {
deps.foo()
} fn main() {
let mut deps = MockFoo::new();
deps.expectfoo().returning(|| 42);
asserteq!(42, my_func(&deps));
}
``` Most often, you will only need to generate mock implementations in test code, and skip this for production code.
For this configuration there are more alternative import paths: A common technique for Rust application development is to divide them into multiple crates.
Entrait does its best to provide great support for this kind of architecture.
This would be very trivial to do and wouldn't even be worth mentioning here if it wasn't for concrete deps. Further up, concrete dependency was mentioned as leaves of a depdendency tree. Let's imagine we have
an app built from two crates: A ```rust
mod lib {
//! lib.rs - pretend this is a separate crate
pub struct LibConfig {
pub foo: String,
} } // main.rs
use implementation::Impl; struct App {
lib_config: lib::LibConfig,
} fn main() {
let app = Impl::new(App {
libconfig: lib::LibConfig {
foo: "value".tostring(),
}
}); }
``` How can this be made to work at all? Let's deconstruct what is happening: The way Entrait lets you get around this problem is how implementations are generated for concrete leafs: ```rust
// desugared entrait:
fn get_foo(config: &LibConfig) -> &str {
&config.foo // (3)
} // generic:
impl // concrete:
impl GetFoo for LibConfig {
fn getfoo(&self) -> &str {
getfoo(self) // calls get_foo, the original function
}
}
``` We see that We end up with quite a dance to actually dig out the config string: Optmized builds should inline a lot of these calls, because all types are fully known at every step. This section lists known limitations of entrait: Cyclic dependency graphs are impossible with entrait.
In fact, this is not a limit of entrait itself, but with Rust's trait solver.
It is not able to prove that a type implements a trait if it needs to prove that it does in order to prove it. While this is a limitation, it is not necessarily a bad one.
One might say that a layered application architecture should never contain cycles.
If you do need recursive algorithms, you could model this as utility functions outside of the entraited APIs of the application. As | Alternative mocking: Mockall
entrait::mockall:*
to have those mock structs autogenerated:[entrait(Foo)]
Conditional compilation of mocks
use entrait::unimock_test::*
puts unimock support inside #[cfg_attr(test, ...)]
.use entrait::mockall_test::*
puts mockall support inside #[cfg_attr(test, ...)]
.Modular applications consisting of several crates
main
which depends on a lib
:#[entrait(pub GetFoo)]
fn get_foo(config: &LibConfig) -> &str {
&config.foo
}
#[entrait(pub LibFunction)]
fn lib_function(deps: &impl GetFoo) {
let foo = deps.get_foo();
}
use lib::LibFunction;
app.lib_function();
LibConfig
.GetFoo
.GetFoo
may call LibFunction
.App
, which contains LibConfig
.Impl<App>
, which means it can call entraited functions.LibFunction
requires the caller to implement GetFoo
.GetFoo
is somehow only implemented for Impl<LibConfig>
, not Impl<App>
.<LibConfig as GetFoo>::get_foo
}
}GetFoo
is implemented for all Impl<T>
where T: GetFoo
.
So the only thing we need to do to get our app working, is to manually implement lib::GetFoo for App
, which would just delegate to self.lib_config.get_foo()
.text
<Impl<App> as lib::LibFunction>::lib_function() lib.rs
=> <Impl<App> as lib::GetFoo>::get_foo() lib.rs
=> <App as lib::GetFoo>::get_foo() main.rs: hand-written implementation
=> <lib::LibConfig as lib::GetFoo>::get_foo() lib.rs
=> lib::get_foo(config) lib.rs
Limitations
Cyclic dependency graphs
Crate compatibility
entrait
is just a macro, it does not pull in any dependencies besides the code needed to execute the macro.
But in order to compile the generated code, some additional dependencies will be needed alongside entrait
.
The following table shows compatible major versions:entrait
| implementation
| unimock
(optional) | mockall
(optional) |
| --------- | ---------------- | -------------------- | -------------------- |
| 0.3
| 0.1
| 0.2
, 0.3
| 0.11
|
| 0.2
| -
| 0.1
| 0.11
|
| 0.1
| -
| -
| 0.11
|