aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/tests/test_injector.py
blob: d6c6d3e88dd9a8aeb6607ad82540c87d5ee41a1e (plain) (blame)
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
94
95
96
97
98
99
100
101
102
103
from typing import Dict, List, Optional
from unittest.mock import Base
from infini.handler import Handler
from infini.injector import Injector
from infini.input import Input
from infini.loader import Loader
from infini.output import Output
from infini.router import Startswith


def test_injector():
    def name(nickname: str, c: int = 0):
        return nickname, c

    def add(a: int, b: int = 0):
        return a + b

    injector = Injector()
    injector.parameters = {"a": 12, "b": 20, "c": 10, "nickname": "苏向夜"}
    assert injector.inject(add)() == 32
    assert injector.output(add) == 32
    assert injector.output(name) == ("苏向夜", 10)


def test_handler_injector():
    input = Input("test_message")

    def absolute(input: Input[str], plain_text: str) -> Output:
        return input.output(
            "text",
            "absolute",
            block=False,
            variables={
                "text": plain_text,
            },
        )

    def absolute_2(input: Input[str], plain_text: Optional[str]) -> Output:
        return input.output(
            "text",
            "absolute",
            block=False,
            variables={
                "text": plain_text,
            },
        )

    handler = Handler()
    handler.handlers = [
        {
            "priority": 2,
            "router": Startswith(""),
            "handler": absolute,
        },
        {
            "priority": 2,
            "router": Startswith(""),
            "handler": absolute_2,
        },
    ]

    core = Loader().into_core()
    core.handler = handler
    core.generator.events = {
        "absolute": "{{ text }}",
    }

    for output in core.input(input):
        assert output == "test_message"


def test_instance_injector():
    class BaseClass: ...

    class Class(BaseClass):
        value = 10

    def test(
        a: int,
        base: BaseClass,
        b: int = 0,
        cls: Optional[BaseClass] = None,
    ):
        assert isinstance(base, Class)
        assert isinstance(cls, Class)
        assert cls.value == 10
        return a + b

    injector = Injector()
    injector.parameters = {"a": 12, "b": 20, "c": 0, "cls": Class(), "base": Class()}

    assert injector.output(test) == 32


def test_complex_injector():
    def test(data: Dict[str, Dict[str, List[str]]]):
        assert isinstance(data, dict)
        return data["value"]

    injector = Injector()
    injector.parameters = {"data": {"value": 32}}

    assert injector.output(test) == 32