"""The questionnaires come out of a session, and come out comparable. Two of these exist because of the same fact: a participant's partner numbers run in the order they met the partners, and that order is a coin flip. Pooling `believed_p1` across participants stacks two different questions. """ import csv import pytest from pe_analysis import measures as M def test_the_key_is_the_published_one(): key = M.tripm_key() assert len(key) == 58 scales = {} for scale, _facet, _rev in key.values(): scales[scale] = scales.get(scale, 0) + 1 assert scales == {"Boldness": 19, "Meanness": 19, "Disinhibition": 20} assert sum(rev for _s, _f, rev in key.values()) == 17 def test_a_reverse_keyed_item_is_flipped_and_a_forward_one_is_not(): key = M.tripm_key() fwd = next(n for n, (s, _f, r) in key.items() if s == "Boldness" and not r) rev = next(n for n, (s, _f, r) in key.items() if s == "Boldness" and r) assert M.score_tripm({f"tripm_{fwd}": 3}, key)["tripm_boldness"] == 3 assert M.score_tripm({f"tripm_{rev}": 3}, key)["tripm_boldness"] == 0 assert M.score_tripm({f"tripm_{rev}": 0}, key)["tripm_boldness"] == 3 def test_scoring_goes_by_item_number_not_by_the_order_asked(): """Each participant sees the items shuffled, so a scorer that walked the answers in order would score a different scale for every participant.""" key = M.tripm_key() answers = {f"tripm_{n}": 2 for n in key} shuffled = dict(reversed(list(answers.items()))) assert M.score_tripm(answers, key) == M.score_tripm(shuffled, key) def test_a_full_questionnaire_reports_a_total_and_a_partial_one_does_not(): key = M.tripm_key() full = M.score_tripm({f"tripm_{n}": 1 for n in key}, key) assert full["tripm_complete"] is True assert full["tripm_n_answered"] == 58 assert full["tripm_total"] is not None partial = M.score_tripm({f"tripm_{n}": 1 for n in list(key)[:20]}, key) assert partial["tripm_complete"] is False assert partial["tripm_n_answered"] == 20 assert partial["tripm_total"] is None, ( "a sum over 20 items is not on the same scale as a sum over 58") def test_skipping_every_item_scores_none_rather_than_zero(): """Zero is the lowest possible score. An unanswered questionnaire that reads as zero puts that participant at the bottom of the distribution.""" out = M.score_tripm({}, M.tripm_key()) for scale in ("boldness", "meanness", "disinhibition"): assert out[f"tripm_{scale}"] is None assert out[f"tripm_{scale}_mean"] is None assert out[f"tripm_{scale}_n"] == 0 assert out["tripm_total"] is None def test_an_out_of_range_or_unparseable_answer_is_dropped_not_counted(): key = M.tripm_key() bold = [n for n, (s, _f, _r) in key.items() if s == "Boldness"][:3] answers = {f"tripm_{bold[0]}": 2, f"tripm_{bold[1]}": 99, f"tripm_{bold[2]}": "no answer", "tripm_notanumber": 1} out = M.score_tripm(answers, key) assert out["tripm_boldness_n"] == 1 assert out["tripm_boldness"] == 2 # --------------------------------------------------------------------------- # Belief and liking. Position depends on the task order; kind does not. # --------------------------------------------------------------------------- def _belief(partners, **answers): return dict(measure="belief_check", partners=partners, **answers) HUNT_FIRST = [{"position": 1, "id": "6725", "kind": "hunt", "where": "the treasure hunt"}, {"position": 2, "id": "P2-1", "kind": "day", "where": "the daytime harvest"}, {"position": 3, "id": "P2-2", "kind": "night", "where": "the Night Harvest"}] HARVEST_FIRST = [{"position": 1, "id": "P2-9", "kind": "day", "where": "the daytime harvest"}, {"position": 2, "id": "P2-8", "kind": "night", "where": "the Night Harvest"}, {"position": 3, "id": "4412", "kind": "hunt", "where": "the treasure hunt"}] def test_the_same_answer_lands_in_the_same_column_whichever_task_ran_first(): """This is the whole point. Two participants who both disbelieved the treasure hunt's partner must both show up in believed_hunt, although one met that partner first and the other met them last.""" a = M._partner_columns(_belief(HUNT_FIRST, believed_p1="No", believed_p2="Yes", believed_p3="Yes"), "believed") b = M._partner_columns(_belief(HARVEST_FIRST, believed_p1="Yes", believed_p2="Yes", believed_p3="No"), "believed") assert a["believed_hunt"] == b["believed_hunt"] == "No" assert a["believed_day"] == b["believed_day"] == "Yes" assert a["believed_night"] == b["believed_night"] == "Yes" # and pooling on position would have mixed them up assert a["believed_p1"] != b["believed_p1"] def test_the_position_columns_are_kept_with_who_they_were_about(): out = M._partner_columns(_belief(HUNT_FIRST, believed_p1="No"), "believed") assert out["believed_p1_id"] == "6725" assert out["believed_p1_kind"] == "hunt" assert out["believed_n_partners"] == 3 def test_liking_is_keyed_by_game_although_its_rows_carry_no_kind(): """The liking record stores only the game's display name. Without the fallback every pooled liking column would be missing.""" rows = [dict(p) for p in HUNT_FIRST] for p in rows: p.pop("kind") out = M._partner_columns( dict(measure="partner_liking", partners=rows, liking_p1=10, liking_p2=20, liking_p3=30), "liking") assert out["liking_hunt"] == 10 assert out["liking_day"] == 20 assert out["liking_night"] == 30 def test_an_unrecognised_game_keeps_its_position_and_adds_no_pooled_column(): rows = [{"position": 1, "id": "x", "where": "the midnight orchard"}] out = M._partner_columns( dict(measure="partner_liking", partners=rows, liking_p1=7), "liking") assert out["liking_p1"] == 7 assert out["liking_p1_kind"] is None assert not any(k.startswith("liking_") and k.split("_")[-1] in ("hunt", "day", "night") for k in out) def test_an_untouched_slider_is_reported_as_untouched(): """Every slider reads 50 until it is moved, so a default and a deliberate midpoint are the same number and only this flag separates them.""" out = M._partner_columns( dict(measure="partner_liking", partners=HUNT_FIRST, liking_p1=50, liking_p1_touched=False), "liking") assert out["liking_p1"] == 50 assert out["liking_p1_touched"] is False # --------------------------------------------------------------------------- # A whole session. # --------------------------------------------------------------------------- @pytest.fixture def session(tmp_path, monkeypatch): """A session file is a msgpack, so the records are stubbed instead.""" recs = [ {"name": "Fatigue_post", "data": {"measure": "fatigue", "when": "post", "fatigue": 40, "fatigue_touched": True}}, {"name": "Effort_impact", "data": {"measure": "effort_impact", "block": "day", "impact_self": 60, "impact_other": 30}}, {"name": "Night_Effort_impact", "data": {"measure": "effort_impact", "block": "night", "impact_self": 10, "impact_other": 20}}, {"name": "PostTask_Belief", "data": _belief(HUNT_FIRST, believed_p1="No", believed_p2="Yes", believed_p3="Yes")}, {"name": "TriPM", "data": dict(measure="tripm", n_items=58, item_order=[], **{f"tripm_{n}": 1 for n in M.tripm_key()})}, {"name": "Demographics", "data": {"measure": "demographics", "n_items": 12, "asked": ["age"], "n_answered": 1, "age": "19"}}, ] monkeypatch.setattr(M.loader, "read_records", lambda _p: recs) monkeypatch.setattr(M.loader, "_session_id", lambda _p: "2026-10-20_12h00.00") monkeypatch.setattr(M.loader, "_pid", lambda _p: "abc123") return tmp_path / "s.msgpack" def test_the_same_battery_after_both_blocks_does_not_overwrite_itself(session): """effort_impact runs after the day task and after the night one with identical field names. Unprefixed, the second silently replaced the first and the day block's answers vanished.""" m = M.measures(session) assert m["day_impact_self"] == 60 assert m["night_impact_self"] == 10 assert m["day_impact_other"] == 30 assert m["night_impact_other"] == 20 def test_a_session_comes_out_as_one_row_with_everything_on_it(session): m = M.measures(session) assert m["session"] == "2026-10-20_12h00.00" assert m["pid"] == "abc123" assert m["believed_hunt"] == "No" assert m["tripm_complete"] is True assert m["demo_age"] == "19" assert m["demo_n_answered"] == 1 assert m["post_fatigue"] == 40 def test_a_frame_of_sessions_keeps_a_missing_measure_as_a_column(session): df = M.measures_frame([session]) assert len(df) == 1 assert df.index.tolist() == ["2026-10-20_12h00.00"] assert df.loc["2026-10-20_12h00.00", "believed_hunt"] == "No" def test_build_carries_the_questionnaires_onto_the_sessions_frame(session, monkeypatch): """The point of the merge: one frame, behaviour and questionnaires.""" import pandas as pd from pe_analysis import loader monkeypatch.setattr(loader, "trials_frame", lambda _p: pd.DataFrame({"session": [], "trial": []})) monkeypatch.setattr(loader, "session_summary", lambda _p: {"session": "2026-10-20_12h00.00", "n_trials": 96}) _trials, sessions = loader.build([session]) row = sessions.iloc[0] assert row["n_trials"] == 96 # pandas boxes it as numpy.bool_, so compare the value assert bool(row["tripm_complete"]) is True assert row["believed_hunt"] == "No" def test_a_questionnaire_field_never_overwrites_a_behavioural_one(session, monkeypatch): """Both sides produce a `pid`. If a questionnaire column could win, a new measure sharing a name would silently redefine a column the models read.""" import pandas as pd from pe_analysis import loader monkeypatch.setattr(loader, "trials_frame", lambda _p: pd.DataFrame({"session": [], "trial": []})) monkeypatch.setattr(loader, "session_summary", lambda _p: {"session": "s", "pid": "from_behaviour"}) _trials, sessions = loader.build([session]) assert sessions.iloc[0]["pid"] == "from_behaviour"