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
9 changed files with 2853 additions and 14 deletions
5
tests/__init__.py
Normal file
5
tests/__init__.py
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
"""Tests for pylimerpc.
|
||||
|
||||
Unit tests use fakes/stub servers (no real LimeSurvey needed);
|
||||
integration tests live in test_integration.py and are skipped by default.
|
||||
"""
|
||||
175
tests/test_config.py
Normal file
175
tests/test_config.py
Normal file
|
|
@ -0,0 +1,175 @@
|
|||
"""Unit tests for pylimerpc.config (pytest)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
|
||||
import pytest
|
||||
|
||||
from pylimerpc.config import LsConfig, load_dotenv, parse_dotenv
|
||||
|
||||
DOTENV = """\
|
||||
# comment line
|
||||
LIMESURVEY_BASE_URL=https://ls.example.com/index.php?r=admin/remotecontrol
|
||||
|
||||
LIMESURVEY_USERNAME=test_user
|
||||
LIMESURVEY_PASSWORD="secret with spaces"
|
||||
LIMESURVEY_TIMEOUT_SECONDS=45
|
||||
LIMESURVEY_OWNER_ID=123
|
||||
"""
|
||||
|
||||
BASE_ENV = {
|
||||
"LIMESURVEY_BASE_URL": "https://ls.example.com/index.php?r=admin/remotecontrol",
|
||||
"LIMESURVEY_USERNAME": "test_user",
|
||||
"LIMESURVEY_PASSWORD": "geheim",
|
||||
}
|
||||
|
||||
|
||||
def test_parse_dotenv(tmp_path):
|
||||
env_file = tmp_path / ".env"
|
||||
env_file.write_text(DOTENV, encoding="utf-8")
|
||||
values = parse_dotenv(env_file)
|
||||
assert values["LIMESURVEY_BASE_URL"] == "https://ls.example.com/index.php?r=admin/remotecontrol"
|
||||
assert values["LIMESURVEY_USERNAME"] == "test_user"
|
||||
# quotes stripped, but inner content (spaces) is preserved
|
||||
assert values["LIMESURVEY_PASSWORD"] == "secret with spaces"
|
||||
assert values["LIMESURVEY_TIMEOUT_SECONDS"] == "45"
|
||||
assert values["LIMESURVEY_OWNER_ID"] == "123"
|
||||
assert not any("comment" in key for key in values)
|
||||
|
||||
|
||||
def test_from_dotenv_leest_bestand(tmp_path):
|
||||
env_file = tmp_path / ".env"
|
||||
env_file.write_text(DOTENV, encoding="utf-8")
|
||||
cfg = LsConfig.from_dotenv(env_file, environ={})
|
||||
assert cfg.base_url == "https://ls.example.com/index.php?r=admin/remotecontrol"
|
||||
assert cfg.username == "test_user"
|
||||
assert cfg.password == "secret with spaces"
|
||||
assert cfg.timeout == 45
|
||||
assert cfg.owner_id == 123
|
||||
assert cfg.group_id is None
|
||||
|
||||
|
||||
def test_from_dotenv_bestaat_niet(tmp_path):
|
||||
with pytest.raises(FileNotFoundError):
|
||||
LsConfig.from_dotenv(tmp_path / "missing.env", environ={})
|
||||
|
||||
|
||||
def test_from_dotenv_verplichte_velden_ontbreken(tmp_path):
|
||||
env_file = tmp_path / ".env"
|
||||
env_file.write_text("LIMESURVEY_BASE_URL=https://x.example.com\n", encoding="utf-8")
|
||||
with pytest.raises(ValueError) as excinfo:
|
||||
LsConfig.from_dotenv(env_file, environ={})
|
||||
msg = str(excinfo.value)
|
||||
assert "LIMESURVEY_USERNAME" in msg
|
||||
assert "LIMESURVEY_PASSWORD" in msg
|
||||
assert "LIMESURVEY_BASE_URL" not in msg # that one was set
|
||||
|
||||
|
||||
def test_parameters_overschrijven_bestand(tmp_path):
|
||||
env_file = tmp_path / ".env"
|
||||
env_file.write_text(DOTENV, encoding="utf-8")
|
||||
cfg = LsConfig.from_dotenv(env_file, environ={}, username="ander", timeout=99)
|
||||
assert cfg.username == "ander"
|
||||
assert cfg.timeout == 99
|
||||
# non-overridden fields come from the file
|
||||
assert cfg.base_url == "https://ls.example.com/index.php?r=admin/remotecontrol"
|
||||
|
||||
|
||||
def test_environment_wint_van_bestand(tmp_path):
|
||||
env_file = tmp_path / ".env"
|
||||
env_file.write_text(DOTENV, encoding="utf-8")
|
||||
environ = dict(BASE_ENV, LIMESURVEY_USERNAME="env_user")
|
||||
cfg = LsConfig.from_dotenv(env_file, environ=environ)
|
||||
assert cfg.username == "env_user"
|
||||
|
||||
|
||||
def test_from_env(monkeypatch):
|
||||
for key, value in BASE_ENV.items():
|
||||
monkeypatch.setenv(key, value)
|
||||
monkeypatch.setenv("LIMESURVEY_TIMEOUT_SECONDS", "15")
|
||||
cfg = LsConfig.from_env()
|
||||
assert cfg.base_url == BASE_ENV["LIMESURVEY_BASE_URL"]
|
||||
assert cfg.username == "test_user"
|
||||
assert cfg.timeout == 15
|
||||
assert cfg.owner_id is None
|
||||
assert cfg.group_id is None
|
||||
|
||||
|
||||
def test_from_env_ontbreekt(monkeypatch):
|
||||
monkeypatch.delenv("LIMESURVEY_BASE_URL", raising=False)
|
||||
monkeypatch.delenv("LIMESURVEY_USERNAME", raising=False)
|
||||
monkeypatch.delenv("LIMESURVEY_PASSWORD", raising=False)
|
||||
with pytest.raises(ValueError) as excinfo:
|
||||
LsConfig.from_env(environ={})
|
||||
assert "LIMESURVEY_BASE_URL" in str(excinfo.value)
|
||||
|
||||
|
||||
def test_timeout_default_en_foutief(tmp_path):
|
||||
env_file = tmp_path / ".env"
|
||||
basis = "LIMESURVEY_BASE_URL=https://x.example.com\nLIMESURVEY_USERNAME=u\nLIMESURVEY_PASSWORD=p\n"
|
||||
env_file.write_text(basis, encoding="utf-8")
|
||||
assert LsConfig.from_dotenv(env_file, environ={}).timeout == 30
|
||||
|
||||
env_file.write_text(basis + "LIMESURVEY_TIMEOUT_SECONDS=abc\n", encoding="utf-8")
|
||||
with pytest.raises(ValueError):
|
||||
LsConfig.from_dotenv(env_file, environ={})
|
||||
|
||||
|
||||
def test_owner_group_optioneel(tmp_path):
|
||||
env_file = tmp_path / ".env"
|
||||
basis = "LIMESURVEY_BASE_URL=https://x.example.com\nLIMESURVEY_USERNAME=u\nLIMESURVEY_PASSWORD=p\n"
|
||||
env_file.write_text(basis + "LIMESURVEY_GROUP_ID=7\n", encoding="utf-8")
|
||||
cfg = LsConfig.from_dotenv(env_file, environ={})
|
||||
assert cfg.owner_id is None
|
||||
assert cfg.group_id == 7
|
||||
|
||||
env_file.write_text(basis + "LIMESURVEY_OWNER_ID=abc\n", encoding="utf-8")
|
||||
with pytest.raises(ValueError):
|
||||
LsConfig.from_dotenv(env_file, environ={})
|
||||
|
||||
|
||||
def test_onbekende_parameter(tmp_path):
|
||||
env_file = tmp_path / ".env"
|
||||
env_file.write_text(DOTENV, encoding="utf-8")
|
||||
with pytest.raises(TypeError):
|
||||
LsConfig.from_dotenv(env_file, environ={}, typo_veld=1)
|
||||
|
||||
|
||||
def test_base_url_moet_http_zijn(tmp_path):
|
||||
env_file = tmp_path / ".env"
|
||||
env_file.write_text(
|
||||
"LIMESURVEY_BASE_URL=ftp://x.example.com\nLIMESURVEY_USERNAME=u\nLIMESURVEY_PASSWORD=p\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
with pytest.raises(ValueError):
|
||||
LsConfig.from_dotenv(env_file, environ={})
|
||||
|
||||
|
||||
def test_load_dotenv_setdefault_en_override(tmp_path, monkeypatch):
|
||||
env_file = tmp_path / ".env"
|
||||
env_file.write_text(DOTENV, encoding="utf-8")
|
||||
monkeypatch.setenv("LIMESURVEY_USERNAME", "already_set")
|
||||
load_dotenv(env_file)
|
||||
assert os.environ["LIMESURVEY_USERNAME"] == "already_set" # env wins (setdefault)
|
||||
load_dotenv(env_file, override=True)
|
||||
assert os.environ["LIMESURVEY_USERNAME"] == "test_user" # file wins
|
||||
|
||||
|
||||
def test_verify_ssl_parsing(tmp_path):
|
||||
env_file = tmp_path / ".env"
|
||||
basis = "LIMESURVEY_BASE_URL=https://x.example.com\nLIMESURVEY_USERNAME=u\nLIMESURVEY_PASSWORD=p\n"
|
||||
env_file.write_text(basis, encoding="utf-8")
|
||||
assert LsConfig.from_dotenv(env_file, environ={}).verify_ssl is True # default = on
|
||||
|
||||
for raw, expected in [("false", False), ("0", False), ("FALSE", False), ("no", False), ("true", True), ("1", True)]:
|
||||
env_file.write_text(basis + f"LIMESURVEY_VERIFY_SSL={raw}\n", encoding="utf-8")
|
||||
assert LsConfig.from_dotenv(env_file, environ={}).verify_ssl is expected
|
||||
|
||||
env_file.write_text(basis + "LIMESURVEY_VERIFY_SSL=jawel\n", encoding="utf-8")
|
||||
with pytest.raises(ValueError):
|
||||
LsConfig.from_dotenv(env_file, environ={})
|
||||
|
||||
# explicit parameter wins
|
||||
env_file.write_text(basis + "LIMESURVEY_VERIFY_SSL=true\n", encoding="utf-8")
|
||||
assert LsConfig.from_dotenv(env_file, environ={}, verify_ssl=False).verify_ssl is False
|
||||
38
tests/test_errors.py
Normal file
38
tests/test_errors.py
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
"""Unit tests for pylimerpc.errors (pytest)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pylimerpc.errors import LsApiError, LsAuthError, LsConnectionError, LsError
|
||||
|
||||
|
||||
def test_api_error_bewaart_originele_rpc_fout():
|
||||
raw = {"code": -32602, "message": "Invalid params"}
|
||||
err = LsApiError(
|
||||
"list_surveys failed",
|
||||
method="list_surveys",
|
||||
rpc_code=raw["code"],
|
||||
rpc_message=raw["message"],
|
||||
raw=raw,
|
||||
)
|
||||
assert isinstance(err, LsError)
|
||||
assert err.method == "list_surveys"
|
||||
assert err.rpc_code == -32602
|
||||
assert err.rpc_message == "Invalid params"
|
||||
assert err.raw == raw
|
||||
assert "list_surveys failed" in str(err)
|
||||
|
||||
|
||||
def test_auth_error_is_een_api_error():
|
||||
err = LsAuthError("login refused", rpc_message="Invalid user name or password!")
|
||||
assert isinstance(err, LsApiError)
|
||||
assert isinstance(err, LsError)
|
||||
assert err.rpc_message == "Invalid user name or password!"
|
||||
|
||||
|
||||
def test_connection_error_bewaart_url_en_cause():
|
||||
cause = OSError("connection timed out")
|
||||
err = LsConnectionError("server onbereikbaar", url="https://ls.example.com", cause=cause)
|
||||
assert isinstance(err, LsError)
|
||||
assert not isinstance(err, LsApiError)
|
||||
assert err.url == "https://ls.example.com"
|
||||
assert err.cause is cause
|
||||
129
tests/test_examples.py
Normal file
129
tests/test_examples.py
Normal file
|
|
@ -0,0 +1,129 @@
|
|||
"""Tests for the example scripts: ASGI app and CLI with a fake LsClient/LsConfig."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from pylimerpc.errors import LsError
|
||||
|
||||
|
||||
class FakeLs:
|
||||
"""Duck-typed replacement for LsClient with canned data."""
|
||||
|
||||
surveys = [
|
||||
{"sid": 1, "surveyls_title": "Test <b>", "active": "Y"},
|
||||
{"sid": 2, "surveyls_title": "Inactief", "active": "N"},
|
||||
]
|
||||
|
||||
def __init__(self, cfg: Any) -> None:
|
||||
pass
|
||||
|
||||
def __enter__(self) -> FakeLs:
|
||||
return self
|
||||
|
||||
def __exit__(self, *args: Any) -> None:
|
||||
return None
|
||||
|
||||
def list_surveys(self) -> list[dict[str, Any]]:
|
||||
return list(self.surveys)
|
||||
|
||||
def export_responses(self, sid: Any, doc_type: str = "csv", output_path: Any = None) -> Path:
|
||||
out = Path(output_path) if output_path else Path("output")
|
||||
if out.is_dir():
|
||||
out = out / f"survey_{sid}_responses.{doc_type}"
|
||||
out.parent.mkdir(parents=True, exist_ok=True)
|
||||
out.write_bytes(b"fake-export")
|
||||
return out
|
||||
|
||||
def list_participants(self, sid: Any, **kwargs: Any) -> list[dict[str, Any]]:
|
||||
return [{"tid": "1", "email": "a@b.c", "token": "tok", "completed": "N"}]
|
||||
|
||||
|
||||
class FakeCfg:
|
||||
@classmethod
|
||||
def from_dotenv(cls, path: Any) -> FakeCfg:
|
||||
return cls()
|
||||
|
||||
|
||||
def _patch(monkeypatch, module) -> None:
|
||||
monkeypatch.setattr(module, "LsClient", FakeLs)
|
||||
monkeypatch.setattr(module, "LsConfig", FakeCfg)
|
||||
|
||||
|
||||
def _run_asgi(app, path: str = "/") -> tuple[int, bytes]:
|
||||
sent: list[dict[str, Any]] = []
|
||||
|
||||
async def receive() -> dict[str, Any]:
|
||||
return {"type": "http.request", "body": b"", "more_body": False}
|
||||
|
||||
async def send(msg: dict[str, Any]) -> None:
|
||||
sent.append(msg)
|
||||
|
||||
asyncio.run(app({"type": "http", "method": "GET", "path": path, "headers": []}, receive, send))
|
||||
status = sent[0]["status"]
|
||||
body = b"".join(m.get("body", b"") for m in sent if m["type"] == "http.response.body")
|
||||
return status, body
|
||||
|
||||
|
||||
# -- ASGI -------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_asgi_index_toont_alleen_actieve_surveys(monkeypatch):
|
||||
import examples.example_asgi as ex
|
||||
|
||||
_patch(monkeypatch, ex)
|
||||
status, body = _run_asgi(ex.app, "/")
|
||||
assert status == 200
|
||||
assert b"Test <b>" in body # HTML-ge-escaped
|
||||
assert b"Inactief" not in body # inactive survey filtered out
|
||||
assert b"<td>1</td>" in body
|
||||
|
||||
|
||||
def test_asgi_health_en_404(monkeypatch):
|
||||
import examples.example_asgi as ex
|
||||
|
||||
_patch(monkeypatch, ex)
|
||||
assert _run_asgi(ex.app, "/health") == (200, b"ok")
|
||||
status, _ = _run_asgi(ex.app, "/anders")
|
||||
assert status == 404
|
||||
|
||||
|
||||
def test_asgi_502_bij_ls_fout(monkeypatch):
|
||||
import examples.example_asgi as ex
|
||||
|
||||
class BrokenLs(FakeLs):
|
||||
def list_surveys(self):
|
||||
raise LsError("stuk")
|
||||
|
||||
monkeypatch.setattr(ex, "LsClient", BrokenLs)
|
||||
monkeypatch.setattr(ex, "LsConfig", FakeCfg)
|
||||
status, body = _run_asgi(ex.app, "/")
|
||||
assert status == 502
|
||||
assert b"stuk" in body
|
||||
|
||||
|
||||
# -- CLI ---------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_cli_export_tokens_surveys(monkeypatch, tmp_path, capsys):
|
||||
import examples.example_cli as cli
|
||||
|
||||
_patch(monkeypatch, cli)
|
||||
|
||||
monkeypatch.setattr(sys, "argv", ["example_cli.py", "export", "--sid", "5", "--out", str(tmp_path)])
|
||||
assert cli.main() == 0
|
||||
assert (tmp_path / "survey_5_responses.csv").read_bytes() == b"fake-export"
|
||||
|
||||
monkeypatch.setattr(sys, "argv", ["example_cli.py", "tokens-lijst", "--sid", "5"])
|
||||
assert cli.main() == 0
|
||||
out = capsys.readouterr().out
|
||||
assert "a@b.c" in out and "tok" in out
|
||||
|
||||
monkeypatch.setattr(sys, "argv", ["example_cli.py", "surveys"])
|
||||
assert cli.main() == 0
|
||||
out = capsys.readouterr().out
|
||||
assert "Test <b>" in out
|
||||
assert "Inactief" not in out # active surveys only
|
||||
78
tests/test_integration.py
Normal file
78
tests/test_integration.py
Normal file
|
|
@ -0,0 +1,78 @@
|
|||
"""Integration tests against a real (local) LimeSurvey instance.
|
||||
|
||||
Skipped by default (pyproject: addopts = -m "not integration").
|
||||
Run them manually with the local endpoint via environment variables:
|
||||
|
||||
LIMESURVEY_BASE_URL='https://localhost/limesurvey/index.php?r=admin/remotecontrol' \
|
||||
LIMESURVEY_USERNAME='...' LIMESURVEY_PASSWORD='...' \
|
||||
.venv/bin/python -m pytest -m integration -v
|
||||
|
||||
Without those variables the tests are skipped.
|
||||
Optional: LIMESURVEY_VERIFY_SSL=false for a test instance with a wrong certificate.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
|
||||
import pytest
|
||||
|
||||
from pylimerpc import LsClient, LsConfig
|
||||
from pylimerpc.errors import LsApiError
|
||||
from pylimerpc.utils import parse_responses_json
|
||||
|
||||
pytestmark = pytest.mark.integration
|
||||
|
||||
|
||||
def _config_from_env() -> LsConfig:
|
||||
base_url = os.environ.get("LIMESURVEY_BASE_URL", "").strip()
|
||||
username = os.environ.get("LIMESURVEY_USERNAME", "").strip()
|
||||
password = os.environ.get("LIMESURVEY_PASSWORD", "").strip()
|
||||
if not (base_url and username and password):
|
||||
pytest.skip(
|
||||
"Set LIMESURVEY_BASE_URL, LIMESURVEY_USERNAME and LIMESURVEY_PASSWORD "
|
||||
"(local LimeSurvey endpoint) to run the integration tests"
|
||||
)
|
||||
timeout = int(os.environ.get("LIMESURVEY_TIMEOUT_SECONDS", "30") or 30)
|
||||
verify_ssl = os.environ.get("LIMESURVEY_VERIFY_SSL", "true").strip().lower() not in ("0", "false", "no", "off")
|
||||
return LsConfig(base_url=base_url, username=username, password=password, timeout=timeout, verify_ssl=verify_ssl)
|
||||
|
||||
|
||||
def test_sessie_openen_list_surveys_eigenschappen_en_sluiten():
|
||||
cfg = _config_from_env()
|
||||
with LsClient(cfg) as ls:
|
||||
assert ls.session_key, "no session key received"
|
||||
surveys = ls.list_surveys()
|
||||
assert isinstance(surveys, list)
|
||||
print(f"\n{len(surveys)} surveys gevonden:")
|
||||
for s in surveys[:10]:
|
||||
print(f" sid={s.get('sid')} | active={s.get('active')} | {s.get('surveyls_title')}")
|
||||
if surveys:
|
||||
sid = surveys[0].get("sid")
|
||||
props = ls.get_survey_properties(sid)
|
||||
assert isinstance(props, dict)
|
||||
assert props.get("sid") in (sid, str(sid), int(str(sid)) if str(sid).isdigit() else sid)
|
||||
print(f" properties van sid={sid}: {sorted(props)[:10]} ...")
|
||||
# context manager released the session cleanly
|
||||
assert ls.session_key is None
|
||||
|
||||
|
||||
def test_export_responses_en_statistieken_readonly():
|
||||
"""Read-only export against the real instance (no data modified)."""
|
||||
cfg = _config_from_env()
|
||||
with LsClient(cfg) as ls:
|
||||
surveys = ls.list_surveys()
|
||||
if not surveys:
|
||||
pytest.skip("no surveys on this instance")
|
||||
sid = surveys[0]["sid"]
|
||||
data = ls.export_responses(sid, doc_type="json")
|
||||
assert isinstance(data, bytes)
|
||||
rows = parse_responses_json(data.decode("utf-8")) if data else []
|
||||
print(f"\nexport_responses sid={sid}: {len(rows)} response-rows, {len(data)} bytes")
|
||||
try:
|
||||
stats = ls.export_statistics(sid, doc_type="json")
|
||||
except LsApiError as exc:
|
||||
# server may return an empty statistics export (statistics off / no permission)
|
||||
pytest.skip(f"export_statistics returned an empty export on this instance: {exc}")
|
||||
assert isinstance(stats, bytes)
|
||||
print(f"export_statistics sid={sid}: {len(stats)} bytes")
|
||||
167
tests/test_responses_tokens.py
Normal file
167
tests/test_responses_tokens.py
Normal file
|
|
@ -0,0 +1,167 @@
|
|||
"""Unit tests for responses.py and tokens.py (FakeRpc, no server) + LsClient wiring."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
|
||||
from pylimerpc import LsClient, LsConfig
|
||||
from pylimerpc.errors import LsApiError, LsAuthError
|
||||
from pylimerpc.responses import export_responses, export_responses_json, export_statistics
|
||||
from pylimerpc.tokens import add_participants, delete_participants, list_participants
|
||||
|
||||
|
||||
class FakeRpc:
|
||||
def __init__(self, *responses: Any) -> None:
|
||||
self.responses = list(responses)
|
||||
self.calls: list[tuple[str, list[Any]]] = []
|
||||
|
||||
def call(self, method: str, params: list[Any]) -> Any:
|
||||
self.calls.append((method, list(params)))
|
||||
item = self.responses.pop(0)
|
||||
if isinstance(item, BaseException):
|
||||
raise item
|
||||
return item
|
||||
|
||||
|
||||
CFG = LsConfig(base_url="https://ls.example.com/index.php?r=admin/remotecontrol", username="u", password="p")
|
||||
|
||||
|
||||
def b64(payload: bytes) -> str:
|
||||
return base64.b64encode(payload).decode("ascii")
|
||||
|
||||
|
||||
# -- responses --------------------------------------------------------------
|
||||
|
||||
|
||||
def test_export_responses_params_en_base64_decode():
|
||||
raw = json.dumps({"responses": [{"id": "1"}]}).encode("utf-8")
|
||||
fake = FakeRpc(b64(raw))
|
||||
data = export_responses(fake, "KEY", "123") # type: ignore[arg-type]
|
||||
assert data == raw
|
||||
# LS7 export_responses: [session_key, sid, doc_type, language, completion, field_map, header]
|
||||
assert fake.calls == [("export_responses", ["KEY", 123, "json", None, "all", "code", "short"])]
|
||||
|
||||
|
||||
def test_export_responses_doc_type_csv_en_output_path(tmp_path):
|
||||
fake = FakeRpc(b64(b"a,b\n1,2\n"))
|
||||
out = export_responses(fake, "KEY", 5, doc_type="csv", output_path=tmp_path / "export.csv") # type: ignore[arg-type]
|
||||
assert isinstance(out, Path)
|
||||
assert out.read_bytes() == b"a,b\n1,2\n"
|
||||
assert fake.calls[0][1][2] == "csv"
|
||||
|
||||
|
||||
def test_export_responses_output_path_is_directory(tmp_path):
|
||||
fake = FakeRpc(b64(b"{}"))
|
||||
out = export_responses(fake, "KEY", 9, doc_type="json", output_path=tmp_path) # type: ignore[arg-type]
|
||||
assert out == tmp_path / "survey_9_responses.json"
|
||||
assert out.exists()
|
||||
|
||||
|
||||
def test_export_responses_json_wrapper():
|
||||
payload = {"responses": [{"id": "1", "Q1": "ja"}, {"id": "2", "Q1": "nee"}]}
|
||||
fake = FakeRpc(b64(json.dumps(payload).encode("utf-8")))
|
||||
rows = export_responses_json(fake, "KEY", 5) # type: ignore[arg-type]
|
||||
assert rows == payload["responses"]
|
||||
|
||||
|
||||
def test_export_responses_status_fout_is_lsautherror():
|
||||
fake = FakeRpc({"status": "Invalid session key"})
|
||||
with pytest.raises(LsAuthError):
|
||||
export_responses(fake, "OUDE-KEY", 5) # type: ignore[arg-type]
|
||||
|
||||
|
||||
def test_export_responses_leeg_resultaat_is_lsapierror():
|
||||
fake = FakeRpc("")
|
||||
with pytest.raises(LsApiError):
|
||||
export_responses(fake, "KEY", 5) # type: ignore[arg-type]
|
||||
|
||||
|
||||
def test_export_statistics_params_en_decode():
|
||||
raw = json.dumps({"statistics": []}).encode("utf-8")
|
||||
fake = FakeRpc(b64(raw))
|
||||
data = export_statistics(fake, "KEY", 7, doc_type="json") # type: ignore[arg-type]
|
||||
assert data == raw
|
||||
# LS7 export_statistics: [session_key, sid, doc_type, language]
|
||||
assert fake.calls == [("export_statistics", ["KEY", 7, "json", None])]
|
||||
|
||||
|
||||
# -- tokens -----------------------------------------------------------------
|
||||
|
||||
|
||||
def test_add_participants_params():
|
||||
participants = [{"email": "a@b.c", "firstname": "A", "lastname": "B"}]
|
||||
fake = FakeRpc([{"tid": "1", "token": "tok123", "email": "a@b.c"}])
|
||||
out = add_participants(fake, "KEY", 5, participants) # type: ignore[arg-type]
|
||||
assert out[0]["token"] == "tok123"
|
||||
assert fake.calls == [("add_participants", ["KEY", 5, participants])]
|
||||
|
||||
|
||||
def test_add_participants_create_token_param_en_typecheck():
|
||||
fake = FakeRpc([])
|
||||
add_participants(fake, "KEY", 5, [], create_token=False) # type: ignore[arg-type]
|
||||
assert fake.calls == [("add_participants", ["KEY", 5, [], False])]
|
||||
with pytest.raises(TypeError):
|
||||
add_participants(fake, "KEY", 5, "not-a-list") # type: ignore[arg-type]
|
||||
|
||||
|
||||
def test_list_participants_normaliseert_en_params():
|
||||
fake = FakeRpc({"participants": [{"tid": "1", "email": "a@b.c"}]})
|
||||
out = list_participants(fake, "KEY", 5) # type: ignore[arg-type]
|
||||
assert out == [{"tid": "1", "email": "a@b.c"}]
|
||||
# LS7 list_participants: [session_key, sid, start, limit] (+ conditions, language)
|
||||
assert fake.calls == [("list_participants", ["KEY", 5, 0, 100000])]
|
||||
|
||||
fake2 = FakeRpc([{"tid": "2"}])
|
||||
out2 = list_participants(fake2, "KEY", 5, start=10, limit=50, conditions={"email": "x"}, language="nl") # type: ignore[arg-type]
|
||||
assert out2 == [{"tid": "2"}]
|
||||
assert fake2.calls == [("list_participants", ["KEY", 5, 10, 50, {"email": "x"}, "nl"])]
|
||||
|
||||
|
||||
def test_delete_participants_params_en_coercitie():
|
||||
fake = FakeRpc({"1": "OK", "2": "OK"})
|
||||
out = delete_participants(fake, "KEY", 5, [1, "2"]) # type: ignore[arg-type]
|
||||
assert out == {"1": "OK", "2": "OK"}
|
||||
# LS7 delete_participants: [session_key, sid, [token_ids]]
|
||||
assert fake.calls == [("delete_participants", ["KEY", 5, [1, 2]])]
|
||||
with pytest.raises(TypeError):
|
||||
delete_participants(fake, "KEY", 5, "not-a-list") # type: ignore[arg-type]
|
||||
|
||||
|
||||
# -- LsClient wiring ----------------------------------------------------------
|
||||
|
||||
|
||||
def test_lsclient_responses_en_tokens_delegeren_met_session_key():
|
||||
raw = b64(json.dumps({"responses": []}).encode("utf-8"))
|
||||
fake = FakeRpc(
|
||||
"KEY", # get_session_key
|
||||
raw, # export_responses
|
||||
raw, # export_statistics
|
||||
[{"tid": "1"}], # add_participants
|
||||
{"participants": [{"tid": "1"}]}, # list_participants
|
||||
{"1": "OK"}, # delete_participants
|
||||
True, # release_session_key
|
||||
)
|
||||
with LsClient(CFG, rpc=fake) as ls: # type: ignore[arg-type]
|
||||
assert isinstance(ls.export_responses(5), bytes)
|
||||
assert isinstance(ls.export_statistics(5), bytes)
|
||||
ls.add_participants(5, [{"email": "a@b.c"}])
|
||||
assert ls.list_participants(5) == [{"tid": "1"}]
|
||||
assert ls.delete_participants(5, [1]) == {"1": "OK"}
|
||||
methods = [c[0] for c in fake.calls]
|
||||
assert methods == [
|
||||
"get_session_key",
|
||||
"export_responses",
|
||||
"export_statistics",
|
||||
"add_participants",
|
||||
"list_participants",
|
||||
"delete_participants",
|
||||
"release_session_key",
|
||||
]
|
||||
# session key is in every call
|
||||
assert fake.calls[1][1][0] == "KEY"
|
||||
assert fake.calls[3][1][1] == 5
|
||||
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
|
||||
156
tests/test_session_surveys.py
Normal file
156
tests/test_session_surveys.py
Normal file
|
|
@ -0,0 +1,156 @@
|
|||
"""Unit tests for session.py, surveys.py and the LsClient context manager (fake RPC, no server)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
|
||||
from pylimerpc import LsClient, LsConfig
|
||||
from pylimerpc.errors import LsApiError, LsAuthError, LsConnectionError, LsError
|
||||
from pylimerpc.session import get_session_key, release_session_key
|
||||
from pylimerpc.surveys import filter_active, get_survey_properties, list_surveys
|
||||
|
||||
|
||||
class FakeRpc:
|
||||
"""Duck-typed replacement for RpcClient: returns pre-set responses."""
|
||||
|
||||
def __init__(self, *responses: Any) -> None:
|
||||
self.responses = list(responses)
|
||||
self.calls: list[tuple[str, list[Any]]] = []
|
||||
|
||||
def call(self, method: str, params: list[Any]) -> Any:
|
||||
self.calls.append((method, list(params)))
|
||||
item = self.responses.pop(0)
|
||||
if isinstance(item, BaseException):
|
||||
raise item
|
||||
return item
|
||||
|
||||
|
||||
CFG = LsConfig(base_url="https://ls.example.com/index.php?r=admin/remotecontrol", username="u", password="p")
|
||||
|
||||
|
||||
# -- session ---------------------------------------------------------------
|
||||
|
||||
|
||||
def test_get_session_key_succes():
|
||||
fake = FakeRpc("KEY123")
|
||||
assert get_session_key(fake, "u", "p") == "KEY123" # type: ignore[arg-type]
|
||||
assert fake.calls == [("get_session_key", ["u", "p"])]
|
||||
|
||||
|
||||
def test_get_session_key_foute_login_is_lsautherror():
|
||||
# LS puts {"status": "..."} in result (not in error) on a failed login
|
||||
fake = FakeRpc({"status": "Invalid user name or password!"})
|
||||
with pytest.raises(LsAuthError) as excinfo:
|
||||
get_session_key(fake, "u", "wrong") # type: ignore[arg-type]
|
||||
assert "Invalid user name or password!" in str(excinfo.value.rpc_message)
|
||||
|
||||
|
||||
def test_release_session_key():
|
||||
fake = FakeRpc(True)
|
||||
assert release_session_key(fake, "KEY123") is True # type: ignore[arg-type]
|
||||
assert fake.calls == [("release_session_key", ["KEY123"])]
|
||||
|
||||
|
||||
# -- surveys ---------------------------------------------------------------
|
||||
|
||||
|
||||
def test_list_surveys_succes():
|
||||
payload = [{"sid": 1, "active": "Y"}, {"sid": 2, "active": "N"}]
|
||||
fake = FakeRpc(payload)
|
||||
out = list_surveys(fake, "KEY") # type: ignore[arg-type]
|
||||
assert out == payload
|
||||
assert fake.calls == [("list_surveys", ["KEY"])]
|
||||
|
||||
|
||||
def test_list_surveys_met_owner_id_param():
|
||||
fake = FakeRpc([])
|
||||
list_surveys(fake, "KEY", owner_id=7) # type: ignore[arg-type]
|
||||
assert fake.calls == [("list_surveys", ["KEY", 7])]
|
||||
|
||||
|
||||
def test_list_surveys_status_fout_is_lsautherror():
|
||||
fake = FakeRpc({"status": "Invalid session key"})
|
||||
with pytest.raises(LsAuthError):
|
||||
list_surveys(fake, "OLD-KEY") # type: ignore[arg-type]
|
||||
|
||||
|
||||
def test_list_surveys_geen_lijst_is_lsapierror():
|
||||
fake = FakeRpc(" weird-value ")
|
||||
with pytest.raises(LsApiError):
|
||||
list_surveys(fake, "KEY") # type: ignore[arg-type]
|
||||
|
||||
|
||||
def test_get_survey_properties_succes_en_sid_coercitie():
|
||||
props = {"sid": 123, "surveyls_title": "Test", "active": "Y", "status": "Y"}
|
||||
fake = FakeRpc(props)
|
||||
out = get_survey_properties(fake, "KEY", "123") # type: ignore[arg-type]
|
||||
assert out == props
|
||||
assert fake.calls == [("get_survey_properties", ["KEY", 123])]
|
||||
|
||||
|
||||
def test_get_survey_properties_met_properties_lijst():
|
||||
fake = FakeRpc({"sid": 5, "surveyls_title": "X"})
|
||||
get_survey_properties(fake, "KEY", 5, properties=["surveyls_title", "active"]) # type: ignore[arg-type]
|
||||
assert fake.calls == [("get_survey_properties", ["KEY", 5, ["surveyls_title", "active"]])]
|
||||
|
||||
|
||||
def test_filter_active():
|
||||
surveys = [{"sid": 1, "active": "Y"}, {"sid": 2, "active": "N"}, {"sid": 3, "active": "1"}]
|
||||
assert [s["sid"] for s in filter_active(surveys)] == [1, 3]
|
||||
|
||||
|
||||
# -- LsClient contextmanager ------------------------------------------------
|
||||
|
||||
|
||||
def test_lsclient_opent_en_sluit_sessie():
|
||||
fake = FakeRpc("KEY", [{"sid": 1, "active": "Y"}], True)
|
||||
with LsClient(CFG, rpc=fake) as ls: # type: ignore[arg-type]
|
||||
assert ls.session_key == "KEY"
|
||||
surveys = ls.list_surveys()
|
||||
assert surveys == [{"sid": 1, "active": "Y"}]
|
||||
assert ls.session_key is None
|
||||
assert fake.calls == [
|
||||
("get_session_key", ["u", "p"]),
|
||||
("list_surveys", ["KEY"]),
|
||||
("release_session_key", ["KEY"]),
|
||||
]
|
||||
|
||||
|
||||
def test_lsclient_sluit_sessie_ook_bij_exceptie():
|
||||
fake = FakeRpc("KEY", LsConnectionError("boom"), True)
|
||||
with pytest.raises(LsConnectionError):
|
||||
with LsClient(CFG, rpc=fake) as ls: # type: ignore[arg-type]
|
||||
ls.list_surveys()
|
||||
assert ls.session_key is None
|
||||
assert fake.calls[-1] == ("release_session_key", ["KEY"])
|
||||
|
||||
|
||||
def test_lsclient_release_falen_gooit_niets():
|
||||
fake = FakeRpc("KEY", LsConnectionError("release stuk"))
|
||||
with LsClient(CFG, rpc=fake): # type: ignore[arg-type]
|
||||
pass
|
||||
# no exception escapes; session is cleaned up
|
||||
assert fake.calls == [("get_session_key", ["u", "p"]), ("release_session_key", ["KEY"])]
|
||||
|
||||
|
||||
def test_lsclient_zonder_sessie_gooit_lserror():
|
||||
ls = LsClient(CFG, rpc=FakeRpc()) # type: ignore[arg-type]
|
||||
with pytest.raises(LsError):
|
||||
ls.list_surveys()
|
||||
|
||||
|
||||
def test_lsclient_list_surveysGebruikt_config_owner_group():
|
||||
cfg = LsConfig(
|
||||
base_url="https://ls.example.com/index.php?r=admin/remotecontrol",
|
||||
username="u",
|
||||
password="p",
|
||||
owner_id=9,
|
||||
group_id=3,
|
||||
)
|
||||
fake = FakeRpc("KEY", [{"sid": 1, "group_id": 3}, {"sid": 2, "group_id": 4}], True)
|
||||
with LsClient(cfg, rpc=fake) as ls: # type: ignore[arg-type]
|
||||
out = ls.list_surveys()
|
||||
assert fake.calls[1] == ("list_surveys", ["KEY", 9])
|
||||
assert [s["sid"] for s in out] == [1] # group_id=3 filtered
|
||||
99
tests/test_utils.py
Normal file
99
tests/test_utils.py
Normal file
|
|
@ -0,0 +1,99 @@
|
|||
"""Unit tests for pylimerpc.utils (pytest)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import json
|
||||
|
||||
import pytest
|
||||
|
||||
from pylimerpc.errors import LsApiError, LsAuthError
|
||||
from pylimerpc.utils import (
|
||||
decode_export_json,
|
||||
is_active_flag,
|
||||
is_filled,
|
||||
normalize_sid,
|
||||
parse_responses_json,
|
||||
raise_for_status,
|
||||
summary_counts,
|
||||
to_int,
|
||||
)
|
||||
|
||||
|
||||
def test_to_int():
|
||||
assert to_int("42") == 42
|
||||
assert to_int(7) == 7
|
||||
assert to_int("") is None
|
||||
assert to_int(None) is None
|
||||
assert to_int("abc") is None
|
||||
|
||||
|
||||
def test_is_active_flag():
|
||||
assert is_active_flag("Y") is True
|
||||
assert is_active_flag("1") is True
|
||||
assert is_active_flag("true") is True
|
||||
assert is_active_flag("N") is False
|
||||
assert is_active_flag(None) is False
|
||||
|
||||
|
||||
def test_is_filled():
|
||||
assert is_filled("x") is True
|
||||
assert is_filled("") is False
|
||||
assert is_filled(" ") is False
|
||||
assert is_filled(None) is False
|
||||
assert is_filled("[]") is False
|
||||
assert is_filled("[]x") is True
|
||||
|
||||
|
||||
def test_normalize_sid():
|
||||
assert normalize_sid("123") == 123
|
||||
assert normalize_sid(5) == 5
|
||||
assert normalize_sid("abc") == "abc"
|
||||
|
||||
|
||||
def test_parse_responses_json_varianten():
|
||||
assert parse_responses_json('{"responses": [{"id": "1"}]}') == [{"id": "1"}]
|
||||
assert parse_responses_json('[{"id": "2"}]') == [{"id": "2"}]
|
||||
assert parse_responses_json('{"id": "3"}') == [{"id": "3"}]
|
||||
|
||||
|
||||
def test_decode_export_json_base64():
|
||||
payload = json.dumps({"responses": [{"id": "1", "Q1": "a"}]}).encode("utf-8")
|
||||
b64 = base64.b64encode(payload).decode("ascii")
|
||||
assert decode_export_json(b64) == [{"id": "1", "Q1": "a"}]
|
||||
assert decode_export_json("") == []
|
||||
assert decode_export_json(None) == []
|
||||
|
||||
|
||||
def test_summary_counts_key_varianten():
|
||||
assert summary_counts({"completed_responses": "3", "responses": "10"}) == (3, 10)
|
||||
assert summary_counts({"completed": 1, "full_responses": 5}) == (1, 5)
|
||||
assert summary_counts({}) == (None, None)
|
||||
|
||||
|
||||
def test_raise_for_status_auth():
|
||||
with pytest.raises(LsAuthError):
|
||||
raise_for_status({"status": "Invalid session key"}, "list_surveys")
|
||||
|
||||
|
||||
def test_raise_for_status_api():
|
||||
with pytest.raises(LsApiError) as excinfo:
|
||||
raise_for_status({"status": "Survey not found"}, "get_survey_properties")
|
||||
assert not isinstance(excinfo.value, LsAuthError)
|
||||
|
||||
|
||||
def test_raise_for_status_met_error_code():
|
||||
# LS returns e.g. {"status": "Error: No survey participant list", "error_code": "ERR_NO_PARTICIPANT_TABLE"}
|
||||
with pytest.raises(LsApiError) as excinfo:
|
||||
raise_for_status(
|
||||
{"status": "Error: No survey participant list", "error_code": "ERR_NO_PARTICIPANT_TABLE"},
|
||||
"list_participants",
|
||||
)
|
||||
assert not isinstance(excinfo.value, LsAuthError)
|
||||
assert "No survey participant list" in str(excinfo.value.rpc_message)
|
||||
|
||||
|
||||
def test_raise_for_status_passthrough():
|
||||
props = {"sid": 1, "status": "Y", "surveyls_title": "X"} # status-key tussen andere keys = géén fout
|
||||
assert raise_for_status(props, "get_survey_properties") == props
|
||||
assert raise_for_status([{"sid": 1}], "list_surveys") == [{"sid": 1}]
|
||||
Loading…
Reference in a new issue