diff options
Diffstat (limited to 'tests')
| -rw-r--r-- | tests/__init__.py | 0 | ||||
| -rw-r--r-- | tests/examples/ndice/infini.toml | 9 | ||||
| -rw-r--r-- | tests/examples/ndice/src/dicer.py | 360 | ||||
| -rw-r--r-- | tests/examples/ndice/src/ndice.py | 156 | ||||
| -rw-r--r-- | tests/examples/ndice/tests.py | 17 | ||||
| -rw-r--r-- | tests/test_core.py | 81 | ||||
| -rw-r--r-- | tests/test_generator.py | 68 | ||||
| -rw-r--r-- | tests/test_handlers.py | 96 | ||||
| -rw-r--r-- | tests/test_injector.py | 103 | ||||
| -rw-r--r-- | tests/test_input.py | 16 | ||||
| -rw-r--r-- | tests/test_interceptor.py | 38 | ||||
| -rw-r--r-- | tests/test_internal.py | 11 | ||||
| -rw-r--r-- | tests/test_loader.py | 47 | ||||
| -rw-r--r-- | tests/test_register.py | 59 | ||||
| -rw-r--r-- | tests/test_workflow.py | 47 |
15 files changed, 0 insertions, 1108 deletions
diff --git a/tests/__init__.py b/tests/__init__.py deleted file mode 100644 index e69de29b..00000000 --- a/tests/__init__.py +++ /dev/null diff --git a/tests/examples/ndice/infini.toml b/tests/examples/ndice/infini.toml deleted file mode 100644 index 5db718a3..00000000 --- a/tests/examples/ndice/infini.toml +++ /dev/null @@ -1,9 +0,0 @@ -[infini] -name = "ndice" -version = "0.1.0" -description = "基础掷骰指令规则包" -license = "Apache-2.0" - -[requirements] - -[dependencies] diff --git a/tests/examples/ndice/src/dicer.py b/tests/examples/ndice/src/dicer.py deleted file mode 100644 index 74bb3714..00000000 --- a/tests/examples/ndice/src/dicer.py +++ /dev/null @@ -1,360 +0,0 @@ -from multilogging import multilogger -from typing import List - -import abc -import re -import random - - -ZERO = 0 -EMPTY_STRING = "" -EMPTY_LIST = [] - -logger = multilogger(name="DicerGirl", payload="Dicer") - - -class BaseDice: - def __init__(self, roll_string: str = EMPTY_STRING) -> None: - self.roll_string = roll_string - self.db = EMPTY_STRING - self.outcome = ZERO - self.display = EMPTY_LIST - - def __repr__(self) -> str: - return self.db.upper() - - @abc.abstractmethod - def parse(self) -> "BaseDice": - raise NotImplementedError - - @abc.abstractmethod - def roll(self) -> int: - """对骰子进行投掷并给出结果""" - raise NotImplementedError - - -class DigitDice(BaseDice): - """数字骰""" - - def __init__(self, roll_string: str = EMPTY_STRING) -> None: - super().__init__(roll_string=roll_string) - if not roll_string.isdigit(): - raise ValueError - - self.parse() - - def parse(self) -> "DigitDice": - self.a = int(self.roll_string) - self.b = 1 - self.db = f"{self.a}" - return self - - def roll(self) -> int: - self.outcome = self.a - self.display = [self.a] - return self.outcome - - -class Dice(BaseDice): - """多面骰""" - - def __init__(self, roll_string: str = "", explode: bool = False) -> None: - super().__init__(roll_string=roll_string) - self.dices = EMPTY_LIST - self.great = False - self.explode = explode - self.parse() - - def parse(self) -> "Dice": - self.dices = [] - split = re.split(r"[dD]", self.roll_string) - - if split[0]: - self.a = int(split[0]) - else: - self.a = 1 - - if split[1]: - self.b = int(split[1]) - else: - self.b = 100 - - self.db = f"{self.a}D{self.b}" - self.dices += [f"D{self.b}"] * self.a - return self - - def roll(self) -> int: - self.results = [] - self.display = [] - - for _ in range(self.a): - result = random.randint(1, self.b) - - if result == 1 and self.explode: - result -= 1 - - if self.explode and self.b == 8: - self.dices.append("D10") - result2 = random.randint(1, 10) - if result2 == 1: - result -= 1 - result += result2 - if result2 == 10: - self.dices.append("D12") - result3 = random.randint(1, 12) - if result3 == 1: - result -= 1 - result += result3 - if result3 == 12: - self.dices.append("D20") - result4 = random.randint(1, 20) - if result4 == 1: - result -= 1 - result += result4 - if result4 == 20: - self.great = True - - self.results.append(result) - self.display.append(result) - - self.outcome = sum(self.results) - return self.outcome - - -class AwardDice(BaseDice): - """奖励骰""" - - def __init__(self, roll_string: str = "") -> None: - super().__init__(roll_string=roll_string) - self.parse() - - def parse(self) -> "AwardDice": - split = re.split(r"[bB]", self.roll_string) - - if split[0]: - self.a = int(split[0]) - else: - self.a = 1 - - self.b = int(split[1]) - self.db = f"{self.a}B{self.b}" - return self - - def roll(self) -> int: - self.results = [] - self.display = [] - - for _ in range(self.a): - ten = [] - for _ in range(self.b): - outcome = Dice("1d10").roll() - outcome = outcome if outcome != 10 else 0 - ten.append(outcome) - - result = Dice("1d100").roll() - ten.append(result // 10) - minten = min(ten) - ten.remove(result // 10) - outcome = minten * 10 + (result % 10) - self.results.append(outcome) - self.display.append([result, ten]) - - self.outcome = sum(self.results) - return self.outcome - - -class PunishDice(BaseDice): - """惩罚骰""" - - def __init__(self, roll_string: str = "") -> None: - super().__init__(roll_string=roll_string) - self.parse() - - def parse(self) -> "PunishDice": - split = re.split(r"[pP]", self.roll_string) - - if split[0]: - self.a = int(split[0]) - else: - self.a = 1 - - self.b = int(split[1]) - self.db = f"{self.a}P{self.b}" - return self - - def roll(self) -> int: - self.results = [] - self.display = [] - - for _ in range(self.a): - ten = [] - for _ in range(self.b): - outcome = Dice("1d10").roll() - outcome = outcome if outcome != 10 else 0 - ten.append(outcome) - - result = Dice("1d100").roll() - ten.append(result // 10) - maxten = max(ten) - ten.remove(result // 10) - outcome = maxten * 10 + (result % 10) - self.results.append(outcome) - self.display.append([result, ten]) - - self.outcome = sum(self.results) - return self.outcome - - -class Dicer: - """掷骰类 - 参数: - roll_string: 标准掷骰表达式 - explode: 是否启用爆炸骰 - 示例: - ```python - dice = Dice("1d10") - dice.roll() - print(dice.outcome) # 输出`1d10`投掷结果 - ``` - """ - - def __init__(self, roll_string: str = EMPTY_STRING, explode: bool = False) -> None: - self.roll_string: str = roll_string - self.explode: bool = explode - self.calc_list: List[str | Dice | DigitDice | AwardDice | PunishDice] = [] - self.results: List[int] = [] - self.display: List[int | List[int]] = [] - self.outcome: int = ZERO - self.great: bool = False - self.dices: List[str] = [] - - def parse(self, roll_string: str = EMPTY_STRING, explode: bool = False): - self.roll_string = roll_string if roll_string else self.roll_string - self.calc_list = [] - self.db = EMPTY_STRING - matches: List[str] = re.findall(r"\d*[a-zA-Z]\w*|\d+|[-+*/]", self.roll_string) - - for match in matches: - if match in ("+", "-", "*", "/", "(", ")"): - self.calc_list.append(match) - self.db += match - elif re.match(r"\d*[dD]\d*", match): - self.calc_list.append(Dice(match, explode=explode)) - self.db += match.upper() - elif re.match(r"\d*[bB]\d+", match): - self.calc_list.append(AwardDice(match)) - self.db += match.upper() - elif re.match(r"\d*[pP]\d+", match): - self.calc_list.append(PunishDice(match)) - self.db += match.upper() - elif re.match(r"\d+", match): - self.calc_list.append(DigitDice(match)) - self.db += match.upper() - else: - raise ValueError(f"骰 {match} 不符合规范.") - - if not matches: - self.calc_list.append(Dice("1d100")) - self.db = "1D100" - - return self - - def roll(self): - self.parse(roll_string=self.roll_string, explode=self.explode) - self.dices = [] - self.display = [] - for index, calc in enumerate(self.calc_list): - if calc in ("+", "-", "*", "/", "(", ")"): - continue - - outcome = calc.roll() - self.calc_list[index] = outcome - self.results.append(outcome) - self.display += calc.display - - if isinstance(calc, Dice) and self.explode: - if calc.great: - self.great = True - - self.dices += calc.dices - - self.outcome = eval("".join(map(str, self.calc_list))) - return self - - def description(self): - def count_integers(lst: list) -> int: - count = 0 - for item in lst: - if isinstance(item, int): - count += 1 - elif isinstance(item, list): - count += count_integers(item) - return count - - results = self.display - len_display = count_integers(self.display) - len_results = count_integers(self.results) - - if len_display <= 10: - results = self.display - elif len_results <= 10: - results = self.results - else: - results = [...] - - return f"{self.db}={results}={self.outcome}" - - def get_results(self): - return self.results - - def detail_expr(self): - return str(self.results) - - def calc(self): - return self.outcome - - def __repr__(self): - return self.db - - -if __name__ == "__main__": - # text = "-10/d2/1d10+2d2-22/2+3p2+2b10-p4/b2/d2" - # dice = Dicer(text) - # print(dice.calc_list) - # dice.roll() - # print(dice.calc_list) - # print(dice.results) - # print(dice.outcome) - roll_strings = { - "1": 1, - "10": 10, - "100": 100, - "-1": -1, - "-10": -10, - "-100": -100, - "1d1": 1, - "10d1": 10, - "100d1": 100, - "10d1+10d1": 20, - "10d1-10d1": 0, - "10d1+10d1+10d1": 30, - "10d1-10d1+10d1": 10, - "10d1-10d1-10d1": -10, - } - for roll_string in roll_strings.keys(): - try: - dice = Dicer().parse(roll_string).roll().roll() - if dice.outcome != roll_strings[roll_string]: - print(dice.description()) - raise ValueError( - f"对于 {roll_string} dice.toal={dice.outcome} 但期待 {roll_strings[roll_string]}" - ) - except ValueError as error: - logger.exception(error) - - try: - roll_string = "d" - dice = Dicer(roll_string).roll() - print(dice.description()) - except ValueError as error: - logger.exception(error) diff --git a/tests/examples/ndice/src/ndice.py b/tests/examples/ndice/src/ndice.py deleted file mode 100644 index 082de9f8..00000000 --- a/tests/examples/ndice/src/ndice.py +++ /dev/null @@ -1,156 +0,0 @@ -# Initialized `__init__.py` generated by ipm. -# Documents at https://ipm.hydroroll.team/ - -from infini.register import Register -from infini.router import Startswith -from infini.input import Input -from infini.output import Output -from .dicer import Dicer - -import re - -register = Register() -register.register_textevent( - "ndice.roll", - "[{{ username }}]掷骰: " - "{% if descs|length == 1 %}" - "{{ descs[0] }}" - "{% else %}" - "{{ db }}=[...]=" - "{% for outcome in outcomes %}" - "{{ outcome }}" - "{% if not loop.last %}, {% endif %}" - "{% endfor %}" - "{% endif %}", -) -register.register_textevent( - "ndice.error.bad_roll_string", "[{{ username }}]掷骰时出现异常, 疑似掷骰表达式错误." -) -register.register_textevent("ndice.error.too_much_round", "[{{ username }}]给入的掷骰轮数超出预期.") -register.register_textevent( - "ndice.error.unknown", - "未知错误: {{ error }}, 可能是掷骰语法异常.\nBUG提交: https://gitee.com/unvisitor/issues", -) -register.register_textevent("ndice.error.bad_round", "多轮检定的轮数应当是整型数.") -register.register_textevent("ndice.error.too_much_round", "多轮检定的轮数超出预期.") - - -def translate_punctuation(string: str) -> str: - punctuation_mapping = { - ",": ",", - "。": ".", - "!": "!", - "?": "?", - ";": ";", - ":": ":", - "“": '"', - "”": '"', - "‘": "'", - "’": "'", - "(": "(", - ")": ")", - "【": "[", - "】": "]", - "《": "<", - "》": ">", - } - for ch_punct, en_punct in punctuation_mapping.items(): - string = string.replace(ch_punct, en_punct) - return string - - -def format_str(message: str, begin=None, lower=True) -> str: - regex = r"[<\[](.*?)[\]>]" - message = str(message).lower() if lower else str(message) - msg = translate_punctuation( - re.sub("\s+", " ", re.sub(regex, "", message)).strip(" ") - ) - if msg.startswith("/"): - msg = "." + msg[1:] - - if begin: - if isinstance(begin, str): - begin = [ - begin, - ] - elif isinstance(begin, tuple): - begin = list(begin) - - begin.sort(reverse=True) - for b in begin: - msg = msg.replace(b, "").lstrip(" ") - - return msg - - -def roll(_: Input, args: str, name: str = None) -> str: - time = 1 - if "#" in args: - args = args.split("#") - - try: - time = int(args[0].strip()) - if time > 20: - return Output( - "text", "ndice.error.too_much_round", variables={"username": name} - ) - except ValueError: - return Output("text", "ndice.error.bad_round", variables={"username": name}) - - if len(args) == 1: - args = "1d100" - else: - args = args[1] - else: - args = args.strip() - - args = args.split() - if len(args) > 1: - reason = args[1] - else: - reason = None - - roll_string = args[0] - descs = [] - outcomes = [] - - try: - dice = Dicer(roll_string).roll() - descs.append(dice.description()) - outcomes.append(dice.outcome) - - for _ in range(time - 1): - dice.roll() - descs.append(dice.description()) - outcomes.append(dice.outcome) - except ValueError: - return Output( - "text", - "ndice.error.bad_roll_string", - status=1, - variables={"username": name}, - ) - - return Output( - "text", - "ndice.roll", - variables={ - "username": name, - "descs": descs, - "outcomes": outcomes, - "db": dice.db, - }, - ) - - -@register.handler(router=Startswith(".r"), priority=0) -def roll_handler(input: Input): - args = format_str(input.get_plain_text(), begin=(".r", ".roll")) - name = input.variables.get("nickname") or "苏向夜" - if not args: - return roll(input, "1d100", name=name) - - try: - return roll(input, args, name=name) - except Exception as error: - return Output("text", "ndice.error.unknown", variables={"error": str(error)}) diff --git a/tests/examples/ndice/tests.py b/tests/examples/ndice/tests.py deleted file mode 100644 index 2a56409b..00000000 --- a/tests/examples/ndice/tests.py +++ /dev/null @@ -1,17 +0,0 @@ -from infini.loader import Loader -from infini.input import Input -from pathlib import Path -from ipm import api -from ipm.models.ipk import InfiniProject - -ipk = InfiniProject() -api.build(".") -api.install(f"dist/{ipk.default_name}", force=True) - -loader = Loader() -loader.load("ndice") -loader.close() - -core = loader.into_core() -for output in core.input(Input(".r3d6", {'nickname':'简律纯'})): - print(output) diff --git a/tests/test_core.py b/tests/test_core.py deleted file mode 100644 index bcab2d4a..00000000 --- a/tests/test_core.py +++ /dev/null @@ -1,81 +0,0 @@ -from infini.core import Core -from infini.generator import Generator -from infini.handler import Handler -from infini.injector import Injector -from infini.input import Input -from infini.interceptor import Interceptor -from infini.output import Output -from infini.router import Contains, Startswith - - -def test_core(): - command_input = Input(".add 1 2") - intercepted_input = Input("这个人叫简律纯.") - valid_input = Input("这个叫苏向夜.") - command_and_valid_input = Input(".echo 苏向夜打爆了简某人的狗头") - - def intercept_jianlvchun(_: Input) -> Input | Output: - return Output("text", "block.jianlvchun", block=True) # TODO 拦截器阻塞标识 - - interceptor = Interceptor() - interceptor.interceptors = [ - { - "priority": 1, - "router": Contains("简律纯"), - "handler": intercept_jianlvchun, - } - ] - - def add(input: Input) -> Output: - result = str(sum(list(map(int, input.get_plain_text().lstrip(".add").split())))) - return Output("text", "test.add", block=False, variables={"result": result}) - - def cmd(_: Input) -> Output: - return Output("text", "test.cmd", block=False) - - handler = Handler() - handler.handlers = [ - { - "priority": 2, - "router": Startswith(".add"), - "handler": add, - }, - { - "priority": 1, - "router": Startswith("."), - "handler": cmd, - }, - ] - - generator = Generator() - generator.events = { - "test.cmd": "cmd", - "test.add": "{{ result }}", - "block.jianlvchun": "检测到违禁词", - } - generator.global_variables = {} - - core = Core() - core.handler = handler - core.interceptor = interceptor - core.pre_interceptor = interceptor - core.generator = generator - core.injector = Injector() - - outputs = set() - for output in core.input(command_input): - outputs.add(output) - assert outputs == {"cmd", "3"} - - count = 0 - for _ in core.input(valid_input): - count += 1 - assert count == 0 - - for output in core.input(intercepted_input): - assert output == "检测到违禁词" - - outputs = set() - for output in core.input(command_and_valid_input): - outputs.add(output) - assert outputs == {"cmd"} diff --git a/tests/test_generator.py b/tests/test_generator.py deleted file mode 100644 index 30ad01bd..00000000 --- a/tests/test_generator.py +++ /dev/null @@ -1,68 +0,0 @@ -from infini.generator import Generator, TextGenerator -from infini.injector import Injector -from infini.output import Output - - -def test_generator(): - generator = TextGenerator() - generator.events = { - "test.event1": "Event1 文本", - } - generator.match(Output("text", "test.event1")) - assert generator.output(Output("text", "test.event1"), Injector()) == "Event1 文本" - - -def test_generator_with_var(): - generator = TextGenerator() - generator.events = { - "test.event1": "Event1 文本: {{ var }}", - } - - assert ( - generator.output( - Output("text", "test.event1", variables={"var": "变量测试"}), Injector() - ) - == "Event1 文本: 变量测试" - ) - - -def test_generator_injector(): - def name(nickname: str = "苏向夜"): - return nickname - - injector = Injector() - injector.parameters = {"a": 12, "b": 20, "c": 0} - - generator = TextGenerator() - generator.events = { - "test.event1": "[{{ card_name }}]Event1 文本: {{ var }}", - } - generator.global_variables = {"card_name": name} - assert ( - generator.output( - Output("text", "test.event1", variables={"var": "变量测试"}), injector - ) - == "[苏向夜]Event1 文本: 变量测试" - ) - -def test_register_generator(): - def name(nickname: str = "苏向夜"): - return nickname - - custom = TextGenerator() - custom.type = "custom_text" - - generator = Generator() - generator.events = { - "test.event1": "[{{ card_name }}]Event1 文本: {{ var }}", - } - generator.generators.update({"custom_text": custom}) - - generator.global_variables = {"card_name": name} - assert ( - generator.output( - Output("custom_text", "test.event1", variables={"var": "变量测试"}), - Injector(), - ) - == "[苏向夜]Event1 文本: 变量测试" - ) diff --git a/tests/test_handlers.py b/tests/test_handlers.py deleted file mode 100644 index 79810ce0..00000000 --- a/tests/test_handlers.py +++ /dev/null @@ -1,96 +0,0 @@ -from infini.handler import Handler -from infini.input import Input -from infini.output import Output -from infini.router import Startswith - - -def test_handler(): - input = Input(".add 1 2") - - def add(input: Input) -> Output: - return Output( - "text", - str(sum(list(map(int, input.get_plain_text().lstrip(".add").split())))), - block=False, - ) - - def cmd(_: Input) -> Output: - return Output("text", "cmd", block=False) - - handler = Handler() - handler.handlers = [ - { - "priority": 2, - "router": Startswith(".add"), - "handler": add, - }, - { - "priority": 1, - "router": Startswith("."), - "handler": cmd, - }, - ] - - names = [] - for output in handler.input(input): - names.append(output.name) - assert names == ["cmd", "3"] - - -def test_handler_block(): - input = Input(".add 1 2") - - def add(input: Input) -> Output: - return Output( - "text", - str(sum(list(map(int, input.get_plain_text().lstrip(".add").split())))), - block=False, - ) - - def cmd(_: Input) -> Output: - return Output("text", "cmd", block=True) - - handler = Handler() - handler.handlers = [ - { - "priority": 2, - "router": Startswith(".add"), - "handler": add, - }, - { - "priority": 1, - "router": Startswith("."), - "handler": cmd, - }, - ] - - names = [] - for output in handler.input(input): - names.append(output.name) - assert names == ["cmd"] - - -def test_handler_interator(): - input = Input(".add 1 2") - - def add(input: Input): - yield Output( - "text", - str(sum(list(map(int, input.get_plain_text().lstrip(".add").split())))), - block=False, - ) - yield Output("text", "ok", block=False) - - handler = Handler() - handler.handlers = [ - { - "priority": 1, - "router": Startswith(".add"), - "handler": add, - }, - ] - - names = [] - for output in handler.input(input): - names.append(output.name) - assert names == ["3", "ok"] diff --git a/tests/test_injector.py b/tests/test_injector.py deleted file mode 100644 index d6c6d3e8..00000000 --- a/tests/test_injector.py +++ /dev/null @@ -1,103 +0,0 @@ -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 diff --git a/tests/test_input.py b/tests/test_input.py deleted file mode 100644 index 88a7ceb5..00000000 --- a/tests/test_input.py +++ /dev/null @@ -1,16 +0,0 @@ -from infini.input import Input - - -def test_new_input_without_vars(): - assert Input("test plain_str").plain_data == "test plain_str" - assert Input("test plain_str").get_plain_text() == "test plain_str" - - -def test_new_input_with_session_id(): - input = Input("test plain_str", variables={"session_id": "test"}) - assert input.get_session_id() == "test" - - -def test_new_input_without_session_id(): - input = Input("test plain_str", variables={"user_id": "test"}) - assert input.get_session_id() == "test" diff --git a/tests/test_interceptor.py b/tests/test_interceptor.py deleted file mode 100644 index ded63471..00000000 --- a/tests/test_interceptor.py +++ /dev/null @@ -1,38 +0,0 @@ -from infini.input import Input -from infini.interceptor import Interceptor -from infini.output import Output -from infini.router import Contains - - -def test_interceptor(): - input = Input("这个人叫简律纯.") - valid_input = Input("这个叫苏向夜.") - - def intercept(_: Input) -> Input | Output: - return Output("text", "block.jianlvchun", block=True) - - interceptor = Interceptor() - interceptor.interceptors = [ - { - "priority": 1, - "router": Contains("简律纯"), - "handler": intercept, - } - ] - for output in interceptor.input(input): - assert isinstance(output, Output) - assert output.name == "block.jianlvchun" - - for valid_output in interceptor.input(valid_input): - assert isinstance(valid_output, Input) - assert valid_output.get_plain_text() == "这个叫苏向夜." - - for output in interceptor.output(Output("text", "none", block=True), "简律纯"): - assert isinstance(output, Output) - assert output.name == "block.jianlvchun" - - for output in interceptor.output( - Output("text", "none", block=True), "这个叫苏向夜." - ): - assert isinstance(output, str) - assert output == "这个叫苏向夜." diff --git a/tests/test_internal.py b/tests/test_internal.py deleted file mode 100644 index 321c9f5c..00000000 --- a/tests/test_internal.py +++ /dev/null @@ -1,11 +0,0 @@ -from infini.internal import require -from ipm import api - -import shutil - - -def test_internal(): - api.new("test_ipk") - registers = require("test_ipk") - assert registers - shutil.rmtree("test_ipk") diff --git a/tests/test_loader.py b/tests/test_loader.py deleted file mode 100644 index 82c1dc7b..00000000 --- a/tests/test_loader.py +++ /dev/null @@ -1,47 +0,0 @@ -from infini.input import Input -from infini.loader import Loader -from infini.output import Output -from infini.register import Register - - -def test_loader(): - blocked_god_input = Input("这是苏向夜的杰作.") - snh_input = Input("撅少年狐!") - - register = Register() - - @register.pre_interceptor("苏向夜", priority=0) - def test_pre_interceptor(_: Input): - return Output("text", "block.sxy", block=True) - - @register.handler("撅少年狐") - def test_handler(_: Input): - return Output("text", "block.snh", block=True) - - register.register_textevent("block.sxy", "不可直呼{{ sxy_id }}的ID") - register.register_textevent("block.snh", "不许撅{{ get_snh_id }}") - - register.register_variable("sxy_id", "苏向夜") - - @register.dynamic_variable() - def get_snh_id(): - return "少年狐" - - @register.interceptor("苏向夜", priority=0) - def test_interceptor(_: Input): - return Output("text", "block.sxy", block=True) - - loader = Loader() - loader.load_from_register(register) - core = loader.into_core() - - for output in core.input(blocked_god_input): - assert output == "不可直呼苏向夜的ID" - - for output in core.input(snh_input): - assert output == "不许撅少年狐" - - -def test_with_loader(): - with Loader() as loader: - loader.into_core() diff --git a/tests/test_register.py b/tests/test_register.py deleted file mode 100644 index 654836f1..00000000 --- a/tests/test_register.py +++ /dev/null @@ -1,59 +0,0 @@ -from infini.core import Core -from infini.generator import Generator -from infini.handler import Handler -from infini.injector import Injector -from infini.input import Input -from infini.interceptor import Interceptor -from infini.output import Output -from infini.register import Register - - -def test_register(): - blocked_god_input = Input("这是苏向夜的杰作.") - snh_input = Input("撅少年狐!") - - register = Register() - - @register.pre_interceptor("苏向夜", priority=0) - def test_pre_interceptor(_: Input): - return Output("text", "block.sxy", block=True) - - @register.handler("撅少年狐") - def test_handler(_: Input): - return Output("text", "block.snh", block=True) - - register.register_textevent("block.sxy", "不可直呼{{ sxy_id }}的ID") - register.register_textevent("block.snh", "不许撅{{ get_snh_id }}") - - register.register_variable("sxy_id", "苏向夜") - - @register.dynamic_variable() - def get_snh_id(): - return "少年狐" - - @register.interceptor("苏向夜", priority=0) - def test_interceptor(_: Input): - return Output("text", "block.sxy", block=True) - - pre_interceptor = Interceptor() - pre_interceptor.interceptors = register.pre_interceptors - handler = Handler() - handler.handlers = register.handlers - generator = Generator() - generator.events = register.events - generator.global_variables = register.global_variables - interceptor = Interceptor() - interceptor.interceptors = register.interceptors - - core = Core() - core.pre_interceptor = pre_interceptor - core.handler = handler - core.generator = generator - core.interceptor = interceptor - core.injector = Injector() - - for output in core.input(blocked_god_input): - assert output == "不可直呼苏向夜的ID" - - for output in core.input(snh_input): - assert output == "不许撅少年狐" diff --git a/tests/test_workflow.py b/tests/test_workflow.py deleted file mode 100644 index 18dab9d5..00000000 --- a/tests/test_workflow.py +++ /dev/null @@ -1,47 +0,0 @@ -from infini.core import Core -from infini.generator import Generator -from infini.handler import Handler -from infini.injector import Injector -from infini.input import Input -from infini.interceptor import Interceptor -from infini.output import Output -from infini.router import Startswith - - -def test_workflow(): - def func_workflow(input: Input): - yield input.output("workflow", "test.workflow", block=True) - - input = Input("testmsg") - - handler = Handler() - handler.handlers = [ - { - "priority": 0, - "router": Startswith(""), - "handler": func_workflow, - } - ] - - interceptor = Interceptor() - interceptor.interceptors = [] - - generator = Generator() - generator.events = { - "test.cmd": "cmd", - "test.add": "{{ result }}", - "block.jianlvchun": "检测到违禁词", - } - generator.global_variables = {} - - core = Core() - core.handler = handler - core.interceptor = interceptor - core.pre_interceptor = interceptor - core.generator = generator - core.injector = Injector() - - for output in core.input(input): - assert isinstance(output, Output) - assert output.type == "workflow" - output.status = 0 |
