PyLimeRPC/tests/test_session_surveys.py
Tammo ter Hark 6822eab467 PyLimeRPC 0.2.0 — prompts.md Prompt 1-4
- responses.py: get_summary() (raw RPC get_summary), count_responses() ->
  frozen ResponseCounts(completed, incomplete, total), export_responses_auto()
  with automatic format fallback (xlsx -> xls -> csv) on IWriter errors
- utils.py: summary_counts_full() -> (completed, incomplete, total) with
  per-LS-version key fallbacks; summary_counts left untouched
- surveys.py: get_survey_by_sid() (dict | None), get_survey_info() ->
  frozen SurveyInfo(sid, title, active)
- tokens.py: documented that extra/custom token attributes (attribute_1, ...)
  pass through unchanged in add_participants/list_participants
- LsClient: get_summary, count_responses, get_survey_by_sid, get_survey_info,
  export_responses_auto; __all__ + re-exports updated
- README: new "Response counts & summary" section + usage examples
- .gitignore: prompts.md added (local-only docs, like werkdocument.md)
- version 0.1.0 -> 0.2.0 (__init__.py + pyproject.toml)
- tests: +27 FakeRpc unit tests (96 passed, 2 deselected)

Generated by Mistral Vibe.
Co-Authored-By: Mistral Vibe <vibe@mistral.ai>
2026-11-20 11:56:03 +01:00

236 lines
8.3 KiB
Python

"""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 (
SurveyInfo,
filter_active,
get_survey_by_sid,
get_survey_info,
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]
# -- get_survey_by_sid / get_survey_info --------------------------------------
SURVEYS = [
{"sid": 111, "surveyls_title": "Survey A", "active": "Y"},
{"sid": "222", "surveyls_title": "Survey B", "active": "N"},
]
def test_get_survey_by_sid_hit_and_miss():
fake = FakeRpc(SURVEYS)
hit = get_survey_by_sid(fake, "KEY", 111) # type: ignore[arg-type]
assert hit == SURVEYS[0]
assert fake.calls == [("list_surveys", ["KEY"])]
fake2 = FakeRpc(SURVEYS)
assert get_survey_by_sid(fake2, "KEY", 999) is None # miss → None, no exception # type: ignore[arg-type]
# string sid matches too
fake3 = FakeRpc(SURVEYS)
assert get_survey_by_sid(fake3, "KEY", "222") == SURVEYS[1] # type: ignore[arg-type]
def test_get_survey_by_sid_owner_and_group_params():
surveys = [{"sid": 1, "group_id": 3}, {"sid": 2, "group_id": 4}]
fake = FakeRpc(surveys)
out = get_survey_by_sid(fake, "KEY", 2, owner_id=7, group_id=3) # type: ignore[arg-type]
assert fake.calls == [("list_surveys", ["KEY", 7])]
assert out is None # sid 2 is in group 4, filtered out by group_id=3
def test_get_survey_by_sid_empty_list_is_none():
fake = FakeRpc([])
assert get_survey_by_sid(fake, "KEY", 5) is None # type: ignore[arg-type]
def test_get_survey_by_sid_status_error_is_lsapierror():
fake = FakeRpc({"status": "Some API problem"})
with pytest.raises(LsApiError) as excinfo:
get_survey_by_sid(fake, "KEY", 5) # type: ignore[arg-type]
assert not isinstance(excinfo.value, LsAuthError)
def test_get_survey_info_hit():
fake = FakeRpc(SURVEYS)
info = get_survey_info(fake, "KEY", 111) # type: ignore[arg-type]
assert info == SurveyInfo(sid=111, title="Survey A", active=True)
fake2 = FakeRpc(SURVEYS)
info2 = get_survey_info(fake2, "KEY", "222") # type: ignore[arg-type]
assert info2 == SurveyInfo(sid=222, title="Survey B", active=False)
def test_get_survey_info_miss_is_none():
fake = FakeRpc(SURVEYS)
assert get_survey_info(fake, "KEY", 999) is None # type: ignore[arg-type]
# -- 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
def test_lsclient_get_survey_by_sid_and_get_survey_info():
fake = FakeRpc("KEY", SURVEYS, SURVEYS, SURVEYS, SURVEYS, True)
with LsClient(CFG, rpc=fake) as ls: # type: ignore[arg-type]
assert ls.get_survey_by_sid(111) == SURVEYS[0]
assert ls.get_survey_by_sid(999) is None
info = ls.get_survey_info("222")
assert info == SurveyInfo(sid=222, title="Survey B", active=False)
assert ls.get_survey_info(999) is None
assert fake.calls == [
("get_session_key", ["u", "p"]),
("list_surveys", ["KEY"]),
("list_surveys", ["KEY"]),
("list_surveys", ["KEY"]),
("list_surveys", ["KEY"]),
("release_session_key", ["KEY"]),
]