PyLimeRPC: package pylimerpc + pyproject + tests/examples (overname van minimalLS)
- nieuwe package `pylimerpc/` (rpc, session, surveys, tokens, responses, errors, utils, config) - pyproject.toml (name PyLimeRPC, versie 0.1.0) - tests/ (69 passed, 2 deselected) en examples/ - .env.example: TLS-verificatie documentatie (LIMESURVEY_VERIFY_SSL) - README/.gitignore bijgewerkt Generated by Mistral Vibe. Co-Authored-By: Mistral Vibe <vibe@mistral.ai>
This commit is contained in:
parent
30fc89e4e2
commit
d7d9dc61bf
1 changed files with 2853 additions and 14 deletions
214
tests/test_rpc.py
Normal file
214
tests/test_rpc.py
Normal file
|
|
@ -0,0 +1,214 @@
|
|||
"""Unit tests for pylimerpc.rpc.
|
||||
|
||||
Uses a stub HTTP server (stdlib http.server in a thread) — no real
|
||||
LimeSurvey needed.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import socket
|
||||
import threading
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from types import SimpleNamespace
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
|
||||
from pylimerpc.errors import LsApiError, LsAuthError, LsConnectionError
|
||||
from pylimerpc.rpc import endpoint_url, rpc_call
|
||||
|
||||
|
||||
class _StubHandler(BaseHTTPRequestHandler):
|
||||
def log_message(self, *args: Any) -> None: # keep test output quiet
|
||||
pass
|
||||
|
||||
def _send_bytes(self, out: bytes, status: int, content_type: str) -> None:
|
||||
self.send_response(status)
|
||||
self.send_header("Content-Type", content_type)
|
||||
self.send_header("Content-Length", str(len(out)))
|
||||
self.end_headers()
|
||||
self.wfile.write(out)
|
||||
|
||||
def _send_json(self, obj: dict, status: int = 200) -> None:
|
||||
self._send_bytes(json.dumps(obj).encode("utf-8"), status, "application/json")
|
||||
|
||||
def do_POST(self) -> None:
|
||||
length = int(self.headers.get("Content-Length") or 0)
|
||||
body = self.rfile.read(length)
|
||||
self.server.last_request = { # type: ignore[attr-defined]
|
||||
"path": self.path,
|
||||
"content_type": self.headers.get("Content-Type"),
|
||||
"body": body,
|
||||
}
|
||||
try:
|
||||
payload = json.loads(body.decode("utf-8"))
|
||||
except json.JSONDecodeError:
|
||||
payload = {}
|
||||
method = payload.get("method")
|
||||
rid = payload.get("id")
|
||||
|
||||
if self.path == "/http500":
|
||||
self._send_bytes(b"<html><body><h1>500 Internal Server Error</h1></body></html>", 500, "text/html")
|
||||
return
|
||||
if self.path == "/badjson":
|
||||
self._send_bytes(b"this is not valid json", 200, "application/json")
|
||||
return
|
||||
if method == "fail_api":
|
||||
self._send_json({"jsonrpc": "2.0", "id": rid, "result": None, "error": {"code": -32602, "message": "Invalid params"}})
|
||||
return
|
||||
if method == "fail_auth":
|
||||
self._send_json({"jsonrpc": "2.0", "id": rid, "result": None, "error": {"code": -32000, "message": "Invalid session key"}})
|
||||
return
|
||||
if method == "with_statistic":
|
||||
self._send_json({"jsonrpc": "2.0", "id": rid, "result": {"ok": True}, "error": None, "statistic": {"duration_ms": 12, "memory": 2048}})
|
||||
return
|
||||
# standaard: echo van method + params
|
||||
self._send_json({"jsonrpc": "2.0", "id": rid, "result": {"method": method, "params": payload.get("params")}, "error": None})
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def stub():
|
||||
server = ThreadingHTTPServer(("127.0.0.1", 0), _StubHandler)
|
||||
thread = threading.Thread(target=server.serve_forever, daemon=True)
|
||||
thread.start()
|
||||
port = server.server_address[1]
|
||||
yield SimpleNamespace(url=f"http://127.0.0.1:{port}", server=server)
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
thread.join(timeout=5)
|
||||
|
||||
|
||||
def test_rpc_call_succes_geeft_result_en_stuurt_juiste_request(stub):
|
||||
result = rpc_call(f"{stub.url}/rpc", "echo", ["a", 1], timeout=5)
|
||||
assert result == {"method": "echo", "params": ["a", 1]}
|
||||
|
||||
req = stub.server.last_request # type: ignore[attr-defined]
|
||||
assert req["path"] == "/rpc"
|
||||
assert req["content_type"] == "application/json"
|
||||
sent = json.loads(req["body"].decode("utf-8"))
|
||||
assert sent["jsonrpc"] == "2.0"
|
||||
assert sent["method"] == "echo"
|
||||
assert sent["params"] == ["a", 1]
|
||||
assert isinstance(sent["id"], int)
|
||||
|
||||
|
||||
def test_api_fout_wordt_lsapierror_met_diagnose(stub):
|
||||
with pytest.raises(LsApiError) as excinfo:
|
||||
rpc_call(f"{stub.url}/rpc", "fail_api", [123], timeout=5)
|
||||
err = excinfo.value
|
||||
assert not isinstance(err, LsAuthError)
|
||||
assert err.rpc_code == -32602
|
||||
assert err.rpc_message == "Invalid params"
|
||||
assert err.method == "fail_api"
|
||||
assert err.http_status == 200
|
||||
assert err.raw == {"code": -32602, "message": "Invalid params"}
|
||||
# method, params and body are in the message → diagnosable
|
||||
assert "fail_api" in str(err)
|
||||
assert "123" in str(err)
|
||||
assert "Invalid params" in str(err)
|
||||
|
||||
|
||||
def test_auth_fout_wordt_lsautherror(stub):
|
||||
with pytest.raises(LsAuthError) as excinfo:
|
||||
rpc_call(f"{stub.url}/rpc", "fail_auth", ["oude-key"], timeout=5)
|
||||
err = excinfo.value
|
||||
assert isinstance(err, LsApiError) # LsAuthError is a subtype
|
||||
assert err.rpc_message == "Invalid session key"
|
||||
|
||||
|
||||
def test_http_foutstatus_wordt_lsconnectionerror_met_body(stub):
|
||||
with pytest.raises(LsConnectionError) as excinfo:
|
||||
rpc_call(f"{stub.url}/http500", "echo", [], timeout=5)
|
||||
err = excinfo.value
|
||||
assert err.http_status == 500
|
||||
assert "500" in str(err)
|
||||
assert err.body is not None and "Internal Server Error" in err.body
|
||||
assert err.cause is not None
|
||||
|
||||
|
||||
def test_ongeldige_json_wordt_lsconnectionerror(stub):
|
||||
with pytest.raises(LsConnectionError) as excinfo:
|
||||
rpc_call(f"{stub.url}/badjson", "echo", [], timeout=5)
|
||||
assert "no valid JSON" in str(excinfo.value)
|
||||
assert excinfo.value.http_status == 200
|
||||
|
||||
|
||||
def test_server_onbereikbaar_wordt_lsconnectionerror():
|
||||
# find a free port and close it → connect is refused
|
||||
sock = socket.socket()
|
||||
sock.bind(("127.0.0.1", 0))
|
||||
port = sock.getsockname()[1]
|
||||
sock.close()
|
||||
url = f"http://127.0.0.1:{port}/rpc"
|
||||
with pytest.raises(LsConnectionError) as excinfo:
|
||||
rpc_call(url, "echo", [], timeout=2)
|
||||
assert excinfo.value.url == url
|
||||
assert excinfo.value.cause is not None
|
||||
assert excinfo.value.http_status is None
|
||||
|
||||
|
||||
def test_statistic_veld_wordt_debug_gelogd(stub, caplog):
|
||||
with caplog.at_level(logging.DEBUG, logger="pylimerpc.rpc"):
|
||||
result = rpc_call(f"{stub.url}/rpc", "with_statistic", [], timeout=5)
|
||||
assert result == {"ok": True}
|
||||
assert any("statistic" in rec.getMessage().lower() and "duration_ms" in rec.getMessage() for rec in caplog.records)
|
||||
|
||||
|
||||
def test_endpoint_url():
|
||||
assert endpoint_url("https://host.nl/limesurvey") == "https://host.nl/limesurvey/index.php?r=admin/remotecontrol"
|
||||
assert endpoint_url("https://host.nl/limesurvey/") == "https://host.nl/limesurvey/index.php?r=admin/remotecontrol"
|
||||
assert endpoint_url("https://host.nl/index.php?r=admin/remotecontrol") == "https://host.nl/index.php?r=admin/remotecontrol"
|
||||
|
||||
|
||||
def test_from_config_verify_ssl_false_maakt_ongeverifieerde_context():
|
||||
import ssl
|
||||
|
||||
from pylimerpc.config import LsConfig
|
||||
from pylimerpc.rpc import RpcClient
|
||||
|
||||
cfg = LsConfig(
|
||||
base_url="https://ls.example.com/index.php?r=admin/remotecontrol",
|
||||
username="u",
|
||||
password="p",
|
||||
verify_ssl=False,
|
||||
)
|
||||
client = RpcClient.from_config(cfg)
|
||||
assert client.ssl_context is not None
|
||||
assert client.ssl_context.verify_mode == ssl.CERT_NONE
|
||||
assert client.ssl_context.check_hostname is False
|
||||
|
||||
# default (verify_ssl=True) → None = urllib's standard verifying context
|
||||
cfg_ok = LsConfig(base_url="https://ls.example.com/index.php?r=admin/remotecontrol", username="u", password="p")
|
||||
assert RpcClient.from_config(cfg_ok).ssl_context is None
|
||||
|
||||
|
||||
def test_rpc_call_geeft_ssl_context_en_timeout_door_aan_urlopen(monkeypatch, stub):
|
||||
import ssl
|
||||
import urllib.request
|
||||
|
||||
captured: dict = {}
|
||||
|
||||
class FakeResp:
|
||||
status = 200
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, *args):
|
||||
return False
|
||||
|
||||
def read(self):
|
||||
return json.dumps({"jsonrpc": "2.0", "id": 1, "result": "ok", "error": None}).encode()
|
||||
|
||||
def fake_urlopen(req, timeout=None, context=None, **kwargs):
|
||||
captured["timeout"] = timeout
|
||||
captured["context"] = context
|
||||
return FakeResp()
|
||||
|
||||
monkeypatch.setattr(urllib.request, "urlopen", fake_urlopen)
|
||||
ctx = ssl.create_default_context()
|
||||
assert rpc_call(f"{stub.url}/rpc", "echo", [], timeout=7, ssl_context=ctx) == "ok"
|
||||
assert captured["timeout"] == 7
|
||||
assert captured["context"] is ctx
|
||||
Loading…
Reference in a new issue