{"id":25272059,"url":"https://github.com/audunhalland/unimock","last_synced_at":"2025-04-09T19:17:06.058Z","repository":{"id":37869135,"uuid":"468544929","full_name":"audunhalland/unimock","owner":"audunhalland","description":"A versatile and developer-friendly trait mocking library","archived":false,"fork":false,"pushed_at":"2025-04-06T21:37:04.000Z","size":953,"stargazers_count":74,"open_issues_count":6,"forks_count":3,"subscribers_count":2,"default_branch":"main","last_synced_at":"2025-04-09T19:17:01.731Z","etag":null,"topics":["mock","rust","testing"],"latest_commit_sha":null,"homepage":"","language":"Rust","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/audunhalland.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2022-03-10T23:39:03.000Z","updated_at":"2025-03-19T12:45:58.000Z","dependencies_parsed_at":"2024-04-07T21:35:55.842Z","dependency_job_id":"07a1bc1c-7fe5-4434-8d99-9984add45e76","html_url":"https://github.com/audunhalland/unimock","commit_stats":{"total_commits":511,"total_committers":1,"mean_commits":511.0,"dds":0.0,"last_synced_commit":"6cf82fde0d9ab94eef510b2712e571d3188ed091"},"previous_names":[],"tags_count":17,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/audunhalland%2Funimock","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/audunhalland%2Funimock/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/audunhalland%2Funimock/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/audunhalland%2Funimock/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/audunhalland","download_url":"https://codeload.github.com/audunhalland/unimock/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248094988,"owners_count":21046770,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["mock","rust","testing"],"created_at":"2025-02-12T12:39:15.906Z","updated_at":"2025-04-09T19:17:06.024Z","avatar_url":"https://github.com/audunhalland.png","language":"Rust","funding_links":[],"categories":[],"sub_categories":[],"readme":"# unimock\n\n[\u003cimg alt=\"crates.io\" src=\"https://img.shields.io/crates/v/unimock.svg?style=for-the-badge\u0026logo=rust\" height=\"20\"\u003e](https://crates.io/crates/unimock)\n[\u003cimg alt=\"docs.rs\" src=\"https://img.shields.io/docsrs/unimock?style=for-the-badge\u0026logo=docs.rs\" height=\"20\"\u003e](https://docs.rs/unimock)\n[\u003cimg alt=\"CI\" src=\"https://img.shields.io/github/actions/workflow/status/audunhalland/unimock/rust.yml?branch=main\u0026style=for-the-badge\u0026logo=github\" height=\"20\"\u003e](https://github.com/audunhalland/unimock/actions?query=branch%3Amain)\n[\u003cimg alt=\"Discord\" src=\"https://img.shields.io/discord/1233771789348507698?style=for-the-badge\u0026logo=discord\" height=\"20\"\u003e](https://discord.gg/nw9ZWP9kvy)\n\n\u003c!-- cargo-rdme start --\u003e\n\n\n`unimock` is a library for defining _mock implementations_ of traits.\n\nMocking, in a broad sense, is a way to control API behaviour during test execution.\n\nThe _uni_ in unimock indicates one-ness: All mockable traits are implemented by a single type, [Unimock](https://docs.rs/unimock/latest/unimock/struct.Unimock.html).\nThis design allows for a great flexibility in coding style, as will be demonstrated further down.\n\nThe first code example is the smallest possible use of unimock:\n\n```rust\nuse unimock::*;\n\n#[unimock]\ntrait Foo {}\n\nfn takes_foo(foo: impl Foo) {}\n\ntakes_foo(Unimock::new(()));\n```\n\n1. `trait Foo` is declared with the `#[unimock]` attribute which makes its behaviour mockable.\n2. `fn takes_foo` accepts some type that implements the trait. This function adheres to zero-cost _Inversion of Control/Dependency Inversion_.\n3. A mock instantiation by calling [`Unimock::new(())`](https://docs.rs/unimock/latest/unimock/struct.Unimock.html#method.new), which crates a [`Unimock`](https://docs.rs/unimock/latest/unimock/struct.Unimock.html) value which is passed into `takes_foo`.\n\nThe [`new`](https://docs.rs/unimock/latest/unimock/struct.Unimock.html#method.new) function takes an argument called `setup` (implementing [`Clause`](https://docs.rs/unimock/latest/unimock/trait.Clause.html)), in this case the unit value `()`.\nThe setup argument is _what behaviour is being mocked_, in this case nothing at all.\n`Foo` contains no methods, so there is no behaviour to mock.\n\n## Methods and behaviour mocking\n\nIn order to be somewhat useful, the traits we abstract over should contain some methods.\nIn a unit test for some function, we'd like to mock the behaviour of that function's dependencies (expressed as trait bounds).\n\nGiven some trait,\n\n```rust\n#[unimock]\ntrait Foo {\n    fn foo(\u0026self) -\u003e i32;\n}\n```\n\nwe would like to tell unimock what `Foo::foo`'s behaviour will be, i.e. what it will return.\nIn order to do that, we first need to refer to the method.\nIn Rust, trait methods aren't reified entities, they are not types nor values, so they cannot be referred to in code.\nWe need to tell unimock to expose a separate mocking API.\nThis API will be created in form of a new module, [which is named](#selecting-a-name-for-the-mock-api) by passing e.g. `api=TraitMock` to the unimock macro invocation.\n\nEach of the trait's original methods will get exported as mock config entrypoints through this module: For example `TraitMock::method`.\n`method` is a type that will implement [`MockFn`](https://docs.rs/unimock/latest/unimock/trait.MockFn.html), which is the entrypoint for creating a [`Clause`](https://docs.rs/unimock/latest/unimock/trait.Clause.html):\n\n```rust\n#[unimock(api=FooMock)]\ntrait Foo {\n    fn foo(\u0026self) -\u003e i32;\n}\n\nfn test_me(foo: impl Foo) -\u003e i32 {\n    foo.foo()\n}\n\nlet clause = FooMock::foo.each_call(matching!()).returns(1337);\n\nassert_eq!(1337, test_me(Unimock::new(clause)));\n```\n\nClause construction is a type-state machine that in this example goes through two steps:\n\n1. `FooMock::foo.each_call(matching!())`: Define a _call pattern_.\n   Each call to `Foo::foo` that matches the empty argument list (i.e. always matching, since the method is parameter-less).\n2. `.returns(1337)`: Each matching call will return the value `1337`.\n\nIn this example there is only one clause.\n\n### Call patterns (matching inputs)\n\nIt is common to want to control how a function will respond in relation to what input is given to it!\nInputs are matched by a function that receives the inputs as a tuple, and returns whether it matched as a `bool`.\nA specific `MockFn` together with an input matcher is referred to as a _call pattern_ from now on.\n\nThe `matching!` macro provides syntax sugar for argument matching.\nIt has a syntax inspired by the [`std::matches`](https://doc.rust-lang.org/std/macro.matches.html) macro.\n\nInputs being matched is a condition that needs to be fulfilled in order for the rest of the call pattern to be evaluated.\n\n### Specifying outputs (responses)\nSpecifying outputs can be done in several ways. The simplest one is `returns(some_value)`.\nDifferent ways of specifying outputs are found in [`build::DefineResponse`](https://docs.rs/unimock/latest/unimock/build/struct.DefineResponse.html).\n\nThere are different constraints acting on return values based on how the clause gets initialized:\n\n* `some_call` is tailored for calls that will happen once. Return values have no [Clone] constraint.\n* `each_call` is tailored for calls that are expected to happen more than once, thus requiring [Clone] on return values.\n* `next_call` is used for [verifying exact call sequences](#verifying-exact-sequence-of-calls), otherwise works similar to `some_call`.\n\n### Mutating inputs\nMany traits uses the argument mutation pattern, where there are one or more `\u0026mut` parameters.\n\nTo access the `\u0026mut` parameters (and mutate them), a function is applied to the call pattern using `answers`:\n\n```rust\nlet mocked = Unimock::new(\n    mock::core::fmt::DisplayMock::fmt\n        .next_call(matching!(_))\n        .answers(\u0026|_, f| write!(f, \"mutation!\"))\n);\n\nassert_eq!(\"mutation!\", format!(\"{mocked}\"));\n```\n\nThe argument to `answers` is a function with the same signature as the method it mocks, including the `self` parameter.\n\n## Combining setup clauses\n`Unimock::new()` accepts as argument anything that implements [Clause].\nBasic setup clauses can be combined into composite clauses by using _tuples_:\n\n```rust\n#[unimock(api=FooMock)]\ntrait Foo {\n    fn foo(\u0026self, arg: i32) -\u003e i32;\n}\n\n#[unimock(api=BarMock)]\ntrait Bar {\n    fn bar(\u0026self, arg: i32) -\u003e i32;\n}\n\nfn test_me(deps: \u0026(impl Foo + Bar), arg: i32) -\u003e i32 {\n    deps.bar(deps.foo(arg))\n}\n\nassert_eq!(\n    42,\n    test_me(\n        \u0026Unimock::new((\n            FooMock::foo\n                .some_call(matching!(_))\n                .answers(\u0026|_, arg| arg * 3),\n            BarMock::bar\n                .some_call(matching!((arg) if *arg \u003e 20))\n                .answers(\u0026|_, arg| arg * 2),\n        )),\n        7\n    )\n);\n\n// alternatively, define _stubs_ for each method.\n// This is a nice way to group methods by introducing a closure scope:\nassert_eq!(\n    42,\n    test_me(\n        \u0026Unimock::new((\n            FooMock::foo.stub(|each| {\n                each.call(matching!(1337)).returns(1024);\n                each.call(matching!(_)).answers(\u0026|_, arg| arg * 3);\n            }),\n            BarMock::bar.stub(|each| {\n                each.call(matching!((arg) if *arg \u003e 20)).answers(\u0026|_, arg| arg * 2);\n            }),\n        )),\n        7\n    )\n);\n```\n\nIn both these examples, the order in which the clauses are specified do not matter, _except for input matching_.\nIn order for unimock to find the correct response, call patterns will be matched in the sequence they were defined.\n\n## Interaction verifications\nUnimock performs interaction verifications using a declarative approach.\nExpected interactions are configured at construction time, using [Clause]s.\nRust makes it possible to automatically verify things because of RAII and the [drop] method, which Unimock implements.\nWhen a Unimock instance goes out of scope, Rust automatically runs its verification rules.\n\nOne verification is always enabled in unimock:\n\n_Each [`MockFn`](https://docs.rs/unimock/latest/unimock/trait.MockFn.html) mentioned in some setup clause must be interacted with at least once._\n\nIf this requirement is not met, Unimock will panic inside its Drop implementation.\nThe reason is to help avoiding \"bit rot\" accumulating over time inside test code.\nWhen refactoring release code, tests should always follow along and not be overly generic.\n\nIn general, clauses do not only encode what behaviour is _allowed_ to happen, but also that this behaviour necessarily _must happen_.\n\n### Optional call count expectations in call patterns\nTo make a call count expectation for a specific call pattern,\n   look at [`Quantify`](build::Quantify) or [`QuantifyReturnValue`](build::QuantifyReturnValue), which have methods like\n   [`once()`](build::Quantify::once),\n   [`n_times(n)`](build::Quantify::n_times) and\n   [`at_least_times(n)`](build::Quantify::at_least_times).\n\nWith exact quantification in place, _output sequence_ verifications can be constructed by chaining combinators:\n\n```rust\neach.call(matching!(_)).returns(1).n_times(2).then().returns(2);\n```\n\nThe output sequence will be `[1, 1, 2, 2, 2, ..]`.\nA call pattern like this _must_ be matched at least 3 times.\n2 times because of the first exact output sequence, then at least one time because of the [`.then()`](build::QuantifiedResponse::then) combinator.\n\n### Verifying exact sequence of calls\nExact call sequences may be expressed using _strictly ordered clauses_.\nUse [`next_call`](MockFn::next_call) to define this kind of call pattern.\n\n```rust\nUnimock::new((\n    FooMock::foo.next_call(matching!(3)).returns(5),\n    BarMock::bar.next_call(matching!(8)).returns(7).n_times(2),\n));\n```\n\nAll clauses constructed by `next_call` are expected to be evaluated in the exact sequence they appear in the clause tuple.\n\nOrder-sensitive clauses and order-insensitive clauses (like [`some_call`](MockFn::some_call)) do not interfere with each other.\nHowever, these kinds of clauses cannot be combined _for the same MockFn_ in a single Unimock value.\n\n\n## Application architecture\n\nWriting larger, testable applications with unimock requires some degree of architectural discipline.\nWe already know how to specify dependencies using trait bounds.\nBut would this scale in practice when several layers are involved?\nOne of the main features of unimock is that all traits are implemented by `Unimock`.\nThis means that trait bounds can be composed, and we can use _one value_ that implements all our dependencies:\n\n```rust\nfn some_function(deps: \u0026(impl A + B + C), arg: i32) {\n    // ..\n}\n```\n\nIn a way, this function resembles a `self`-receiving function.\nThe `deps` argument is how the function abstracts over its dependencies.\nLet's keep this call convention and let it scale a bit by introducing two layers:\n\n```rust\nuse std::any::Any;\n\ntrait A {\n    fn a(\u0026self, arg: i32) -\u003e i32;\n}\n\ntrait B {\n    fn b(\u0026self, arg: i32) -\u003e i32;\n}\n\nfn a(deps: \u0026impl B, arg: i32) -\u003e i32 {\n    deps.b(arg) + 1\n}\n\nfn b(deps: \u0026impl Any, arg: i32) -\u003e i32 {\n    arg + 1\n}\n```\n\nThe dependency from `fn a` to `fn b` is completely abstracted away, and in test mode the `deps: \u0026impl X` gets substituted with `deps: \u0026Unimock`.\nBut Unimock is only concerned with the _testing_ side of the picture.\nThe previous code snippet is at the extreme end of the loosely-coupled scale: _No coupling at all!_\nIt shows that unimock is merely a piece in a larger picture.\nTo wire all of this together into a full-fledged runtime solution, without too much boilerplate, reach for the _[entrait pattern](https://docs.rs/entrait)_.\n\n### Gated mock implementation\nIf the trait definition, the uses of the trait bound and the tests all live within the same crate, it's possible to _gate_ the macro invocation:\n\n```rust\n#[cfg_attr(test, unimock(api = FooMock))]\ntrait Foo {}\n```\n\n### Combining release code and mocks: Partial mocks\nUnimock can be used to create arbitrarily deep integration tests, mocking away layers only indirectly used.\nFor that to work, unimock needs to know how to call the \"real\" implementation of traits.\n\nSee the documentation of [`new_partial`](https://docs.rs/unimock/latest/unimock/struct.Unimock.html#method.new_partial) to see how this works.\n\nAlthough this can be implemented with unimock directly, it works best with a higher-level macro like [`entrait`](https://docs.rs/entrait).\n\n### `no_std`\nUnimock can be used in a `no_std` environment. The `\"std\"` feature is enabled by default, and can be removed to enable `no_std`.\n\nThe `no_std` environment depends on [alloc](https://doc.rust-lang.org/alloc/) and requires a global allocator.\nSome unimock features rely on a working implementation of Mutex, and the `spin-lock` feature enables this for `no_std`.\nThe `critical-section` feature is also required for `no_std`.\nThese two features will likely merge into one in some future breaking release.\n\n\n## Mock APIs for central crates\nUnimock works well when the trait being abstracted over is defined in the same code base as the once that contains the test.\nThe Rust Orphan Rule ensures that a Unimock user cannot define a mock implementation for a trait that is upstream to their project.\n\nFor this reason, Unimock has started to move in a direction where it itself defines mock APIs for central crates.\n\nThese mock APIs can be found in [mock].\n\n\n## Misc\n\n#### What kinds of things can be mocked with unimock?\n* Traits with any number of methods\n* Traits with generic parameters, although these cannot be lifetime constrained (i.e. need to satisfy `T: 'static`).\n* Traits with associated types and constants, using `#[unimock(type T = Foo; const FOO: T = value;)]` syntax.\n* Methods with any self receiver (`self`, `\u0026self`, `\u0026mut self` or arbitrary (e.g. `self: Rc\u003cSelf\u003e`)).\n* Methods that take reference inputs.\n* Methods returning values borrowed from self.\n* Methods returning references to arguments.\n* Methods returning `Option\u003c\u0026T\u003e`, `Result\u003c\u0026T, E\u003e` or `Vec\u003c\u0026T\u003e` for any `T` that is borrowed from `self`.\n* Methods returning any tuple combination of self-borrowed or owned elements up to 4 elements.\n* Methods returning a type containing lifetime parameters. For a mocked return they will have to be `'static`.\n* Generic methods using either explicit generic params or argument-position `impl Trait`.\n* Methods that are `async` or return `impl Future`.\n* `async_trait`-annotated traits.\n\n#### What kinds of traits or methods cannot be mocked?\n* Static methods, i.e. no `self` receiver. Static methods with a _default body_ are accepted though, but not mockable.\n\n#### Selecting a name for the mock `api`\nDue to [macro hygiene](https://en.wikipedia.org/wiki/Hygienic_macro),\n    unimock tries to avoid autogenerating any new identifiers that might accidentally create undesired namespace collisions.\nTo avoid user confusion through conjuring up new identifier names out of thin air, the name of the mocking API therefore has to be user-supplied.\nAlthough the user is free to choose any name, unimock suggests following a naming convention.\n\nThe entity being mocked is a trait, but the mocking API is a module.\nThis introduces a conflict in naming convention style, since traits use CamelCase but modules use snake_case.\n\n_The suggested naming convention is using the name of the trait (e.g. `Trait`) postfixed with `Mock`: The resulting module should be called `TraitMock`._\n\nThis will make it easier to discover the API, as it shares a common prefix with the name of the trait.\n\n#### Methods with default implementations\nMethods with default implementations use _delegation by default_.\nThis means that if a default-implementation-method gets called without having been mentioned in a clause, unimock delegates to its default implementation instead of inducing a panic.\nQuite often, a typical default implementation will itself delegate back to a _required_ method.\n\nThis means that you have control over which part of the trait API you want to mock, the high level or the low level part.\n\n#### Associated types\nAssociated types in traits may be specified using the `type` keyword in the unimock macro:\n\n```rust\n#[unimock(api = TraitMock, type A = i32; type B = String;)]\ntrait Trait {\n    type A;\n    type B;\n}\n```\n\nWorking with associated types in a mock environment like Unimock has its limitations.\nThe nature of associated types is that there is one type per implementation, and there is only one mock implementation, so the type must be chosen carefully.\n\n#### Associated constants\nAssociated constants in traits may be specified using the `const` keyword in the unimock macro:\n\n```rust\n#[unimock(api = TraitMock, const FOO: i32 = 42;)]\ntrait Trait {\n    const FOO: i32;\n}\n```\n\nJust like with associated types in Unimock, associated constants have the limitation where there is one value of the const per implementation,\nand there is only one mock implementation, so the value must be chosen carefully.\n\n\n## Project goals\n#### Use only safe Rust\nUnimock respects the memory safety and soundness provided by Rust.\nSometimes this fact can lead to less than optimal ergonomics.\n\nFor example, in order to use `.returns(value)`, the value must (generally) implement `Clone`, `Send`, `Sync` and `'static`.\nIf it's not all of those things, the slightly longer `.answers(\u0026|_| value)` can be used instead.\n\n#### Keep the amount of generated code to a minimum\nThe unimock API is mainly built around generics and traits, instead of being macro-generated.\nAny mocking library will likely always require _some_ degree of introspective metaprogramming (like macros),\n  but doing too much of that is likely to become more confusing to users, as well as taking longer to compile.\nThe `#[unimock]` macro does the minimal things to fill out a few simple trait impls, and that's it. There are no\ncomplex functions or structs that need to be generated.\n\nThere is a downside to this approach, though.\nRust generics aren't infinitely flexible,\n  so sometimes it's possible to misconfigure a mock in a way that the type system is unable to catch up front,\n  resulting in runtime (or rather, test-time) failures.\n\nAll things considered, this tradedoff seems sound, because this is only testing, after all.\n\n#### Use nice, readable APIs\nUnimock's mocking API has been designed to read like natural english sentences.\n\nThis was a fun design challenge, but it arguably also has some real value.\nIt is assumed that code is quicker (and perhaps more fun) to read and write when it resembles real language.\n\n\u003c!-- cargo-rdme end --\u003e\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Faudunhalland%2Funimock","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Faudunhalland%2Funimock","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Faudunhalland%2Funimock/lists"}