File size: 6,532 Bytes
1f942d5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24bab97
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4573fbe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0d46751
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
"""Assignment must survive a participant restarting the task.

This is the property the Pavlovia shelf's orderMap protected: a participant who
reloads or restarts has to land on the same condition, or the counterbalancing
is destroyed without anyone noticing. Here it comes from determinism rather than
stored state, so these tests pin determinism down.
"""
import csv
import subprocess
import sys

import pytest

import allocation as A
import effort_design as D
import make_allocation as M


# --- repeat starts -----------------------------------------------------------

@pytest.mark.parametrize("pid", ["0001", "1125", "SONA12345", "sona-99", "A7B3"])
def test_assignment_is_identical_on_every_start(pid):
    """A SONA participant who quits and restarts must get the same arm."""
    first = A.assign(pid)
    for _ in range(5):
        assert A.assign(pid) == first


@pytest.mark.parametrize("pid", ["0001", "SONA12345"])
def test_assignment_survives_a_server_restart(pid):
    """Fresh interpreters, because a Space cold start is a fresh interpreter."""
    got = {subprocess.run(
        [sys.executable, "-c",
         f"import allocation as A, effort_design as D;"
         f"a=A.assign({pid!r});print(a['night'],a['night_order'],D._seed_from_pid({pid!r}))"],
        capture_output=True, text=True, check=True).stdout.strip()
        for _ in range(3)}
    assert len(got) == 1, f"assignment differs across processes: {got}"


def test_trial_order_also_survives_a_restart():
    """The arm is only half of it -- the trial order must be stable too."""
    a = D.make_trials(8, "SONA12345")
    b = D.make_trials(8, "SONA12345")
    assert [(t["condition"], t["workSide"]) for t in a] == \
           [(t["condition"], t["workSide"]) for t in b]


# --- the pre-registered table ------------------------------------------------

def test_table_pids_are_exactly_balanced():
    rows = M.build(per_group=125)
    assert len(rows) == 250
    cells = {}
    for r in rows:
        cells[(r["group"], r["night"], r["night_order"])] = \
            cells.get((r["group"], r["night"], r["night_order"]), 0) + 1
    assert set(cells.values()) == {25}, cells


def test_arms_are_balanced_within_each_group():
    """Night must be orthogonal to group, since group is recruited not assigned."""
    rows = M.build(per_group=125)
    for g in ("0", "1"):
        nights = [r["night"] for r in rows if r["group"] == g]
        counts = {n: nights.count(n) for n in set(nights)}
        assert counts == {"": 25, "1": 25, "2": 25, "both": 50}
        orders = [r["night_order"] for r in rows
                  if r["group"] == g and r["night"] == "both"]
        assert orders.count("12") == orders.count("21") == 25


def test_table_and_runtime_agree():
    """allocation.py must report what allocation.csv actually says."""
    with open(A.TABLE, newline="", encoding="utf-8") as f:
        for row in csv.DictReader(f):
            got = A.assign(row["pid"])
            assert got["source"] == "table"
            assert got["night"] == row["night"]
            assert got["group"] == row["group"]


def test_unknown_pid_falls_back_to_hash_not_an_error():
    got = A.assign("SONA-not-in-table")
    assert got["source"] == "hash"
    assert (got["night"], got["night_order"]) in [(n, o or "12") for n, o in A.ARMS]


def test_runtime_arms_match_the_generator():
    assert A.ARMS == M.ARMS


def test_group_is_not_inferred_from_a_sona_id():
    """A SONA id starting with 0 is not a group 0 participant."""
    assert A.group_of("0001") == "0"
    assert A.group_of("0999999-sona") == ""


@pytest.mark.parametrize("night,expected", [
    ("both", [1, 2]), ("1", [1]), ("2", [2]), ("", []),
])
def test_night_list(night, expected):
    assert A.night_list(night) == expected


# --- survey-platform links ---------------------------------------------------

def test_unsubstituted_placeholders_are_rejected():
    """A SONA link opened outside SONA arrives as a literal %SURVEY_CODE%.

    Taking it literally is silent and expensive: everyone affected shares one
    pid, and therefore one condition, one seed, one trial order and one data
    directory, overwriting each other.
    """
    import web_app as W
    for bad in ["%SURVEY_CODE%", "%survey_code%", "%PARTICIPANT_ID%",
                "${e://Field/pid}", "PROLIFIC_PID", "", "   ", None]:
        assert W._clean_pid(bad) is None, bad


def test_real_sona_codes_are_accepted():
    import web_app as W
    for good in ["0001", "SONA12345", "abc-123", "9f3a7c"]:
        assert W._clean_pid(f"  {good} ") == good


def test_distinct_sona_codes_get_distinct_orders():
    """The whole point of %SURVEY_CODE%: one code per participant."""
    orders = {tuple(t["condition"] for t in D.make_trials(8, f"SONA{i}"))
              for i in range(20)}
    assert len(orders) == 20


def test_sona_return_url_always_carries_the_survey_code():
    """SONA grants credit from survey_code; without one it credits nobody.

    The researcher may paste the completion URL with the code templated, with
    an unsubstituted %SURVEY_CODE% (SONA rewrites the study link, not a
    parameter inside it), or with no code at all. All three must normalise.
    """
    import web_app as W
    base = ("https://uni.sona-systems.com/webstudy_credit.aspx"
            "?experiment_id=123&credit_token=abc")
    want = base + "&survey_code=S99"
    assert W._sona_return_url(base, "S99") == want
    assert W._sona_return_url(base + "&survey_code=%SURVEY_CODE%", "S99") == want
    assert W._sona_return_url(base + "&survey_code=STALE", "S99") == want
    assert W._sona_return_url("", "S99") == ""


def test_sona_return_url_escapes_the_code():
    import web_app as W
    got = W._sona_return_url("https://u.sona-systems.com/c.aspx?experiment_id=1", "a b&c")
    assert "survey_code=a%20b%26c" in got


# --- one switch for which study this is --------------------------------------

@pytest.mark.parametrize("study,dyad", [("dyad", True), ("sona", False), (None, False)])
def test_study_switch_sets_dyad_mode(study, dyad, monkeypatch):
    """dyad_mode and the SONA ending were separate flags, which allowed a
    dyadic consent form with a SONA ending, or the reverse. One switch cannot
    disagree with itself. SONA is the default: nobody should be asked about
    their child unless the link says this is that study."""
    import web_app as W
    store = {}
    if study:
        store["study"] = study
    resolved = store.get("study", "sona")
    assert (resolved == "dyad") is dyad