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>
This commit is contained in:
Tammo ter Hark 2026-11-20 11:56:03 +01:00
commit 6822eab467
5 changed files with 633 additions and 24 deletions

View file

@ -52,7 +52,7 @@ def test_sessie_openen_list_surveys_eigenschappen_en_sluiten():
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]} ...")
print(f" properties of sid={sid}: {sorted(props)[:10]} ...")
# context manager released the session cleanly
assert ls.session_key is None

View file

@ -11,7 +11,15 @@ 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.responses import (
ResponseCounts,
count_responses,
export_responses,
export_responses_auto,
export_responses_json,
export_statistics,
get_summary,
)
from pylimerpc.tokens import add_participants, delete_participants, list_participants
@ -90,6 +98,131 @@ def test_export_statistics_params_en_decode():
assert fake.calls == [("export_statistics", ["KEY", 7, "json", None])]
# -- get_summary / count_responses -------------------------------------------
SUMMARY = {"completed_responses": 14, "incomplete_responses": 41, "full_responses": 55}
def test_get_summary_params_and_dict():
fake = FakeRpc(SUMMARY)
out = get_summary(fake, "KEY", "123") # type: ignore[arg-type]
assert out == SUMMARY
# LS7 get_summary: [session_key, sid] (numeric sid string → int)
assert fake.calls == [("get_summary", ["KEY", 123])]
def test_get_summary_status_error_is_lsapierror():
fake = FakeRpc({"status": "Invalid surveyid"})
with pytest.raises(LsApiError) as excinfo:
get_summary(fake, "KEY", 5) # type: ignore[arg-type]
assert not isinstance(excinfo.value, LsAuthError)
assert "Invalid surveyid" in str(excinfo.value.rpc_message)
def test_get_summary_non_dict_is_lsapierror():
fake = FakeRpc(["not", "a", "dict"])
with pytest.raises(LsApiError):
get_summary(fake, "KEY", 5) # type: ignore[arg-type]
fake2 = FakeRpc("ok")
with pytest.raises(LsApiError):
get_summary(fake2, "KEY", 5) # type: ignore[arg-type]
def test_count_responses_counts():
fake = FakeRpc(SUMMARY)
counts = count_responses(fake, "KEY", 5) # type: ignore[arg-type]
assert counts == ResponseCounts(completed=14, incomplete=41, total=55)
assert (counts.completed, counts.incomplete, counts.total) == (14, 41, 55)
assert fake.calls == [("get_summary", ["KEY", 5])]
def test_count_responses_is_frozen():
fake = FakeRpc(SUMMARY)
counts = count_responses(fake, "KEY", 5) # type: ignore[arg-type]
with pytest.raises(AttributeError):
counts.completed = 99 # type: ignore[misc]
def test_count_responses_fallback_keys_and_total_sum():
# without full_responses → total = completed + incomplete
fake = FakeRpc({"responses_completed": "3", "in_progress_responses": 2})
counts = count_responses(fake, "KEY", 5) # type: ignore[arg-type]
assert (counts.completed, counts.incomplete, counts.total) == (3, 2, 5)
fake2 = FakeRpc({"completed": 1})
counts2 = count_responses(fake2, "KEY", 5) # type: ignore[arg-type]
assert (counts2.completed, counts2.incomplete, counts2.total) == (1, 0, 1)
def test_count_responses_missing_or_invalid_values_become_zero():
fake = FakeRpc({})
counts = count_responses(fake, "KEY", 5) # type: ignore[arg-type]
assert (counts.completed, counts.incomplete, counts.total) == (0, 0, 0)
fake2 = FakeRpc({"completed_responses": "abc", "incomplete_responses": None})
counts2 = count_responses(fake2, "KEY", 5) # type: ignore[arg-type]
assert (counts2.completed, counts2.incomplete, counts2.total) == (0, 0, 0)
# -- export_responses_auto (format fallback) -----------------------------------
def _iwriter_error(doc_type: str) -> LsApiError:
msg = f"Writer for {doc_type} should implement IWriter"
return LsApiError(msg, method="export_responses", rpc_message=msg)
def test_export_responses_auto_fallback_xlsx_to_xls():
raw = b64(b"a,b\n1,2\n")
fake = FakeRpc(_iwriter_error("xlsx"), raw)
data, used = export_responses_auto(fake, "KEY", 5) # type: ignore[arg-type]
assert used == "xls"
assert data == b"a,b\n1,2\n"
# both calls are export_responses; doc_type order was xlsx, then xls
assert [c[0] for c in fake.calls] == ["export_responses", "export_responses"]
assert [c[1][2] for c in fake.calls] == ["xlsx", "xls"]
assert all(c[1][0] == "KEY" and c[1][1] == 5 for c in fake.calls)
def test_export_responses_auto_first_format_works():
raw = b64(b"{}")
fake = FakeRpc(raw)
data, used = export_responses_auto(fake, "KEY", 5, formats=("json", "csv")) # type: ignore[arg-type]
assert used == "json"
assert data == b"{}"
assert len(fake.calls) == 1
def test_export_responses_auto_all_formats_fail_raises_lsapierror():
fake = FakeRpc(_iwriter_error("xlsx"), _iwriter_error("xls"), _iwriter_error("csv"))
with pytest.raises(LsApiError) as excinfo:
export_responses_auto(fake, "KEY", 5) # type: ignore[arg-type]
assert "IWriter" in str(excinfo.value)
assert [c[1][2] for c in fake.calls] == ["xlsx", "xls", "csv"]
def test_export_responses_auto_non_iwriter_error_raises_immediately():
fake = FakeRpc(LsApiError("some other problem", method="export_responses", rpc_message="some other problem"))
with pytest.raises(LsApiError) as excinfo:
export_responses_auto(fake, "KEY", 5) # type: ignore[arg-type]
assert "some other problem" in str(excinfo.value)
assert len(fake.calls) == 1 # no fallback on non-IWriter errors
def test_export_responses_auto_iwriter_in_str_exc_only():
# IWriter only in str(exc), not in rpc_message → still fallback
fake = FakeRpc(LsApiError("Writer for xlsx should implement IWriter"), b64(b"x"))
data, used = export_responses_auto(fake, "KEY", 5, formats=("xlsx", "xls")) # type: ignore[arg-type]
assert (used, data) == ("xls", b"x")
def test_export_responses_auto_with_output_path_returns_path(tmp_path):
fake = FakeRpc(_iwriter_error("xlsx"), b64(b"a,b\n"))
out = tmp_path / "export.bin"
data, used = export_responses_auto(fake, "KEY", 5, output_path=out) # type: ignore[arg-type]
assert used == "xls"
assert isinstance(data, Path)
assert data == out and out.read_bytes() == b"a,b\n"
# -- tokens -----------------------------------------------------------------
@ -122,6 +255,29 @@ def test_list_participants_normaliseert_en_params():
assert fake2.calls == [("list_participants", ["KEY", 5, 10, 50, {"email": "x"}, "nl"])]
def test_add_participants_extra_attributes_pass_through():
# surveys can define custom token attributes (attribute_1, ...); they are
# sent to LS unchanged as extra keys in the participant dict
participants = [{"email": "a@b.c", "firstname": "A", "attribute_1": "blue", "attribute_2": "42"}]
fake = FakeRpc([{"tid": "1", "token": "tok123"}])
out = add_participants(fake, "KEY", 5, participants) # type: ignore[arg-type]
assert out[0]["token"] == "tok123"
assert fake.calls == [("add_participants", ["KEY", 5, participants])]
assert fake.calls[0][1][2][0]["attribute_1"] == "blue"
def test_list_participants_extra_attributes_come_back_unchanged():
rows = [
{"tid": "1", "email": "a@b.c", "token": "t1", "attribute_1": "blue", "attribute_2": "42"},
{"tid": "2", "email": "d@e.f", "token": "t2"}, # no extra attributes here
]
fake = FakeRpc({"participants": rows})
out = list_participants(fake, "KEY", 5) # type: ignore[arg-type]
assert out == rows
assert out[0]["attribute_1"] == "blue"
assert "attribute_1" not in out[1]
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]
@ -165,3 +321,37 @@ def test_lsclient_responses_en_tokens_delegeren_met_session_key():
# session key is in every call
assert fake.calls[1][1][0] == "KEY"
assert fake.calls[3][1][1] == 5
def test_lsclient_get_summary_and_count_responses():
fake = FakeRpc(
"KEY", # get_session_key
SUMMARY, # get_summary
SUMMARY, # count_responses → get_summary
True, # release_session_key
)
with LsClient(CFG, rpc=fake) as ls: # type: ignore[arg-type]
assert ls.get_summary(5) == SUMMARY
counts = ls.count_responses("5")
assert isinstance(counts, ResponseCounts)
assert (counts.completed, counts.incomplete, counts.total) == (14, 41, 55)
assert fake.calls == [
("get_session_key", ["u", "p"]),
("get_summary", ["KEY", 5]),
("get_summary", ["KEY", 5]),
("release_session_key", ["KEY"]),
]
def test_lsclient_export_responses_auto():
fake = FakeRpc("KEY", _iwriter_error("xlsx"), b64(b"x"), True)
with LsClient(CFG, rpc=fake) as ls: # type: ignore[arg-type]
data, used = ls.export_responses_auto(5)
assert (used, data) == ("xls", b"x")
assert [c[0] for c in fake.calls] == [
"get_session_key",
"export_responses",
"export_responses",
"release_session_key",
]
assert [c[1][2] for c in fake.calls[1:3]] == ["xlsx", "xls"]

View file

@ -64,7 +64,7 @@ class _StubHandler(BaseHTTPRequestHandler):
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
# default: echo of method + params
self._send_json({"jsonrpc": "2.0", "id": rid, "result": {"method": method, "params": payload.get("params")}, "error": None})

View file

@ -9,7 +9,14 @@ 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
from pylimerpc.surveys import (
SurveyInfo,
filter_active,
get_survey_by_sid,
get_survey_info,
get_survey_properties,
list_surveys,
)
class FakeRpc:
@ -101,6 +108,61 @@ def test_filter_active():
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 ------------------------------------------------
@ -154,3 +216,21 @@ def test_lsclient_list_surveysGebruikt_config_owner_group():
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"]),
]

View file

@ -16,6 +16,7 @@ from pylimerpc.utils import (
parse_responses_json,
raise_for_status,
summary_counts,
summary_counts_full,
to_int,
)
@ -71,6 +72,24 @@ def test_summary_counts_key_varianten():
assert summary_counts({}) == (None, None)
def test_summary_counts_full_basis():
summary = {"completed_responses": 14, "incomplete_responses": 41, "full_responses": 55}
assert summary_counts_full(summary) == (14, 41, 55)
def test_summary_counts_full_fallback_keys_and_total_sum():
# without full_responses → total = completed + incomplete
assert summary_counts_full({"responses_completed": "3", "in_progress_responses": 2}) == (3, 2, 5)
assert summary_counts_full({"completed": 1}) == (1, 0, 1)
# full_responses wins when present
assert summary_counts_full({"completed_responses": 2, "incomplete_responses": 3, "full_responses": 99}) == (2, 3, 99)
def test_summary_counts_full_missing_or_invalid_is_zero():
assert summary_counts_full({}) == (0, 0, 0)
assert summary_counts_full({"completed_responses": "abc", "incomplete_responses": None}) == (0, 0, 0)
def test_raise_for_status_auth():
with pytest.raises(LsAuthError):
raise_for_status({"status": "Invalid session key"}, "list_surveys")