aboutsummaryrefslogtreecommitdiff
path: root/tests/fixtures/models.py
blob: 671c7b3bbad5e90e894f0e49d6cb9954292bde30 (plain)
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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
from datetime import timezone, datetime

import pytest

from jb.models.event import MTurkEvent
from generalresearchutils.pg_helper import PostgresConfig

from datetime import datetime, timezone, timedelta
from typing import Optional, TYPE_CHECKING, Callable, Generator
from jb.managers.amt import AMTManager
from jb.models.assignment import AssignmentStub, Assignment
from generalresearchutils.currency import USDCent
from jb.models.definitions import HitStatus, HitReviewStatus, AssignmentStatus
from jb.models.hit import HitType, HitQuestion, Hit
from tests import generate_amt_id
from psycopg.errors import ForeignKeyViolation

if TYPE_CHECKING:
    from jb.managers.hit import HitQuestionManager, HitTypeManager, HitManager
    from jb.managers.assignment import AssignmentManager


# --- MTurk Event ---


@pytest.fixture
def mturk_event(
    amt_assignment_id: str, amt_hit_id: str, amt_hit_type_id: str
) -> MTurkEvent:
    now = datetime.now(tz=timezone.utc)
    return MTurkEvent(
        event_type="AssignmentSubmitted",
        event_timestamp=now,
        amt_assignment_id=amt_assignment_id,
        amt_hit_type_id=amt_hit_type_id,
        amt_hit_id=amt_hit_id,
    )


# --- Question ---


@pytest.fixture
def question() -> HitQuestion:
    return HitQuestion(url="https://jamesbillings67.com/work/", height=1200)


@pytest.fixture
def question_record(hqm: "HitQuestionManager", question: HitQuestion) -> HitQuestion:
    return hqm.get_or_create(question)


# --- HITType ---


@pytest.fixture
def hit_type() -> HitType:
    return HitType(
        title="Awesome Surveys!",
        description="Give us your opinion",
        reward=USDCent(5),
        keywords="market,research,amazing",
        min_active=10,
    )


@pytest.fixture
def hit_type_record(
    pg_config: PostgresConfig, htm: "HitTypeManager", hit_type: HitType
) -> Generator[HitType, None, None]:

    hit_type.amt_hit_type_id = generate_amt_id()

    ht = htm.get_or_create(hit_type)

    yield ht

    try:
        with pg_config.make_connection() as conn:
            with conn.cursor() as c:
                c.execute("DELETE FROM mtwerk_hittype WHERE id=%s", (ht.id,))
                conn.commit()

    except ForeignKeyViolation:
        pass  # DB gets dropped anyway, don't care


@pytest.fixture
def hit_type_record_with_amt_id(
    pg_config: PostgresConfig, htm: "HitTypeManager", hit_type: HitType
) -> Generator[HitType, None, None]:
    # This is a real hit type I've previously registered with amt (sandbox).
    # It will always exist
    hit_type.amt_hit_type_id = "3217B3DC4P5YW9DRV9R3X8O56V041J"

    # Get or create our db
    ht = htm.get_or_create(hit_type)

    yield ht

    try:
        with pg_config.make_connection() as conn:
            with conn.cursor() as c:
                c.execute("DELETE FROM mtwerk_hittype WHERE id=%s", (ht.id,))
                conn.commit()

    except ForeignKeyViolation:
        pass  # DB gets dropped anyway, don't care


# --- HIT ---


@pytest.fixture
def hit(
    amt_hit_id: str, amt_hit_type_id: str, amt_group_id: str, question: HitQuestion
) -> Hit:
    now = datetime.now(tz=timezone.utc)

    return Hit.model_validate(
        dict(
            amt_hit_id=amt_hit_id,
            amt_hit_type_id=amt_hit_type_id,
            amt_group_id=amt_group_id,
            status=HitStatus.Assignable,
            review_status=HitReviewStatus.NotReviewed,
            creation_time=now,
            expiration=now + timedelta(days=3),
            hit_question_xml=question.xml,
            qualification_requirements=[],
            max_assignments=1,
            assignment_pending_count=0,
            assignment_available_count=1,
            assignment_completed_count=0,
            description="Description",
            keywords="Keywords",
            reward=USDCent(5),
            title="Title",
            question_id=question.id,
            hit_type_id=None,
        )
    )


@pytest.fixture
def hit_record(
    pg_config: PostgresConfig,
    hm: "HitManager",
    question_record: HitQuestion,
    hit_type_record: HitType,
    hit: Hit,
    amt_hit_id: str,
) -> Generator[Hit, None, None]:
    """
    Returns a hit that exists in our db, but does not in amazon (the amt ids
        are random). The mtwerk_hittype and mtwerk_question records will also
        exist (in the db)
    """

    hit.hit_type_id = hit_type_record.id
    hit.amt_hit_id = amt_hit_id
    hit.question_id = question_record.id

    hm.create(hit)

    yield hit

    try:
        with pg_config.make_connection() as conn:
            with conn.cursor() as c:
                c.execute("DELETE FROM mtwerk_hit WHERE id=%s", (hit.id,))
                conn.commit()

    except ForeignKeyViolation:
        pass  # DB gets dropped anyway, don't care


@pytest.fixture
def hit_in_amt(
    amtm: AMTManager,
    hm: "HitManager",
    question_record: HitQuestion,
    hit_type_record_with_amt_id: HitType,
) -> Hit:
    # Actually create a new HIT in amt (sandbox)
    hit = amtm.create_hit_with_hit_type(
        hit_type=hit_type_record_with_amt_id, question=question_record
    )

    # Create it in the DB
    hm.create(hit)
    return hit


# --- Assignment ---


@pytest.fixture
def assignment_stub(
    hit: Hit, amt_assignment_id: str, amt_worker_id: str
) -> AssignmentStub:
    now = datetime.now(tz=timezone.utc)
    return AssignmentStub(
        amt_assignment_id=amt_assignment_id,
        amt_hit_id=hit.amt_hit_id,
        amt_worker_id=amt_worker_id,
        status=AssignmentStatus.Submitted,
        modified_at=now,
        created_at=now,
    )


@pytest.fixture
def assignment_stub_record(
    pg_config: PostgresConfig,
    am: "AssignmentManager",
    hit_record: Hit,
    assignment_stub: AssignmentStub,
) -> Generator[AssignmentStub, None, None]:
    """
    Returns an AssignmentStub that exists in our db, but does not in
    amazon (the amt ids are random). The mtwerk_hit, mtwerk_hittype, and
    mtwerk_question records will also exist (in the db)
    """
    assignment_stub.hit_id = hit_record.id
    am.create_stub(stub=assignment_stub)

    yield assignment_stub

    try:
        with pg_config.make_connection() as conn:
            with conn.cursor() as c:
                c.execute(
                    "DELETE FROM mtwerk_assignment WHERE id=%s", (assignment_stub.id,)
                )
                conn.commit()

    except ForeignKeyViolation:
        pass  # DB gets dropped anyway, don't care


@pytest.fixture
def assignment(assignment_factory: Callable[..., Assignment]) -> Assignment:
    return assignment_factory()


@pytest.fixture
def assignment_record(
    pg_config: PostgresConfig,
    hit_record: Hit,
    assignment_record_factory: Callable[..., Assignment],
) -> Generator[Assignment, None, None]:
    assignment = assignment_record_factory(hit_id=hit_record.id)

    yield assignment

    try:
        with pg_config.make_connection() as conn:
            with conn.cursor() as c:
                c.execute("DELETE FROM mtwerk_assignment WHERE id=%s", (assignment.id,))
                conn.commit()

    except ForeignKeyViolation:
        pass  # DB gets dropped anyway, don't care


@pytest.fixture
def assignment_factory(hit_record: Hit) -> Callable[[Optional[str]], Assignment]:

    def _inner(amt_worker_id: Optional[str] = None) -> Assignment:
        now = datetime.now(tz=timezone.utc)
        amt_assignment_id = generate_amt_id()
        amt_worker_id = amt_worker_id or generate_amt_id()

        return Assignment(
            amt_assignment_id=amt_assignment_id,
            amt_hit_id=hit_record.amt_hit_id,
            amt_worker_id=amt_worker_id,
            status=AssignmentStatus.Submitted,
            modified_at=now,
            created_at=now,
            accept_time=now,
            auto_approval_time=now,
            submit_time=now,
        )

    return _inner


@pytest.fixture
def assignment_record_factory(
    am: "AssignmentManager", assignment_factory: Callable[..., Assignment]
) -> Callable[..., Assignment]:

    def _inner(hit_id: int, amt_worker_id: Optional[str] = None) -> Assignment:
        a = assignment_factory(amt_worker_id=amt_worker_id)
        a.hit_id = hit_id
        am.create_stub(a)
        am.update_answer(a)
        return a

    return _inner