PyLimeRPC/tests/test_responses_tokens.py

357 lines
14 KiB
Python
Raw Permalink Normal View History

"""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 (
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
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])]
# -- 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 -----------------------------------------------------------------
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_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]
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
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"]