foxygit / RPA-Remisser Log in
commits tags

/tests/test_assist.py · 2.73 KB

raw
import pytest

from rpa import assist


class _Block:
    def __init__(self, data):
        self.type = "tool_use"
        self.name = "emit_flow"
        self.input = data


class _Resp:
    def __init__(self, data):
        self.content = [_Block(data)]


class _FakeMessages:
    def __init__(self, replies):
        self._replies = list(replies)
        self.calls = []

    def create(self, **kwargs):
        self.calls.append(kwargs)
        return _Resp(self._replies.pop(0))


class _FakeClient:
    def __init__(self, replies):
        self.messages = _FakeMessages(replies)


def _patch(monkeypatch, replies):
    client = _FakeClient(replies)
    monkeypatch.setattr(assist, "_client", lambda: client)
    return client


def test_generate_flow_happy_path(monkeypatch):
    _patch(monkeypatch, [{
        "nodes": [{"id": "n1", "type": "goto", "url": "https://example.com/"}],
        "edges": [],
        "start": "n1",
        "settings": {},
        "explanation": "Går till example.com.",
    }])
    result = assist.generate_flow("gå till example.com")
    assert result["nodes"][0]["url"] == "https://example.com/"
    assert result["start"] == "n1"
    assert result["explanation"] == "Går till example.com."


def test_generate_flow_keeps_subflows(monkeypatch):
    _patch(monkeypatch, [{
        "nodes": [{"id": "n1", "type": "call_flow", "target": "#hjalp"}],
        "edges": [],
        "start": "n1",
        "settings": {},
        "subflows": [{
            "id": "hjalp", "name": "Hjälp",
            "nodes": [{"id": "s1", "type": "wait", "seconds": 1}], "edges": [],
        }],
        "explanation": "Anropar en subgraf.",
    }])
    result = assist.generate_flow("gör en subgraf och anropa den")
    assert result["subflows"][0]["id"] == "hjalp"
    assert result["nodes"][0]["type"] == "call_flow"


def test_generate_flow_repairs_once(monkeypatch):
    client = _patch(monkeypatch, [
        {"nodes": [{"id": "n1", "type": "goto"}], "edges": [], "settings": {}},  # url saknas -> ogiltigt
        {"nodes": [{"id": "n1", "type": "goto", "url": "https://ok.se/"}], "edges": [], "settings": {}},
    ])
    result = assist.generate_flow("gå till ok.se")
    assert result["nodes"][0]["url"] == "https://ok.se/"
    assert len(client.messages.calls) == 2


def test_generate_flow_gives_up_after_repair(monkeypatch):
    _patch(monkeypatch, [
        {"nodes": [{"id": "n1", "type": "goto"}], "edges": [], "settings": {}},
        {"nodes": [{"id": "n1", "type": "goto"}], "edges": [], "settings": {}},
    ])
    with pytest.raises(assist.AssistError):
        assist.generate_flow("trasigt")


def test_empty_instruction_rejected(monkeypatch):
    _patch(monkeypatch, [])
    with pytest.raises(assist.AssistError):
        assist.generate_flow("   ")