aboutsummaryrefslogtreecommitdiff
path: root/tests/prevent_circular.rs
blob: 2abbac73f5289e39e0b1ad2a93b7a3418e3a6c1e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#![deny(clippy::all, clippy::pedantic)]
#![allow(clippy::disallowed_names)]

use syrette::errors::di_container::DIContainerError;
use syrette::errors::injectable::InjectableError;
use syrette::ptr::TransientPtr;
use syrette::{injectable, DIContainer};

#[derive(Debug)]
struct Foo
{
    _bar: TransientPtr<Bar>,
}

#[injectable]
impl Foo
{
    fn new(bar: TransientPtr<Bar>) -> Self
    {
        Self { _bar: bar }
    }
}

#[derive(Debug)]
struct Bar
{
    _foo: TransientPtr<Foo>,
}

#[injectable]
impl Bar
{
    fn new(foo: TransientPtr<Foo>) -> Self
    {
        Self { _foo: foo }
    }
}

macro_rules! assert_match {
    ($target: expr, $pattern: pat => $expr: expr) => {{
        let target = $target;

        // Not all pattern variables will be used here
        #[allow(unused_variables)]
        {
            assert!(matches!(&target, $pattern));
        }

        match target {
            $pattern => $expr,
            _ => {
                unreachable!();
            }
        }
    }};
}

#[test]
fn prevent_circular_works()
{
    let mut di_container = DIContainer::new();

    di_container.bind::<Foo>().to::<Foo>().expect("Expected Ok");
    di_container.bind::<Bar>().to::<Bar>().expect("Expected Ok");

    let err = di_container.get::<Foo>().expect_err("Expected Err");

    let container_err_a = assert_match!(
        err,
        DIContainerError::BindingResolveFailed {
            reason: InjectableError::ResolveFailed { reason, affected: _ },
            interface: _
        } => *reason
    );

    let container_err_b = assert_match!(
        container_err_a,
        DIContainerError::BindingResolveFailed {
            reason: InjectableError::ResolveFailed { reason, affected: _ },
            interface: _
        } => *reason
    );

    assert!(matches!(
        container_err_b,
        DIContainerError::BindingResolveFailed {
            reason: InjectableError::DetectedCircular {
                dependency_history: _
            },
            interface: _
        }
    ));
}