chenzhaoyang
2025-12-17 063da0bf961e1d35e25dc107f883f7492f4c5a7c
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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
import json
from unittest import TestCase
 
import pytest
import requests
import requests_mock
from django.urls import reverse
from projects.models import Project
from webhooks.models import Webhook, WebhookAction
from webhooks.utils import emit_webhooks, emit_webhooks_for_instance, run_webhook
 
 
@pytest.fixture
def organization_webhook(configured_project):
    organization = configured_project.organization
    uri = 'http://127.0.0.1:8000/api/organization/'
    return Webhook.objects.create(
        organization=organization,
        project=None,
        url=uri,
    )
 
 
@pytest.fixture
def project_webhook(configured_project):
    organization = configured_project.organization
    uri = 'http://127.0.0.1:8000/api/project/'
    return Webhook.objects.create(
        organization=organization,
        project=configured_project,
        url=uri,
    )
 
 
@pytest.fixture
def ml_start_training_webhook(configured_project):
    organization = configured_project.organization
    uri = 'http://0.0.0.0:9090/webhook'
    return Webhook.objects.create(
        organization=organization,
        project=configured_project,
        url=uri,
    )
 
 
@pytest.mark.django_db
def test_run_webhook(setup_project_dialog, organization_webhook):
    webhook = organization_webhook
    with requests_mock.Mocker(real_http=True) as m:
        m.register_uri('POST', webhook.url)
        run_webhook(organization_webhook, WebhookAction.PROJECT_CREATED, {'data': 'test'})
 
    request_history = m.request_history
    assert len(request_history) == 1
    assert request_history[0].method == 'POST'
    assert request_history[0].url == organization_webhook.url
    TestCase().assertDictEqual(request_history[0].json(), {'action': WebhookAction.PROJECT_CREATED, 'data': 'test'})
 
 
@pytest.mark.django_db
def test_emit_webhooks(setup_project_dialog, organization_webhook):
    webhook = organization_webhook
    with requests_mock.Mocker(real_http=True) as m:
        m.register_uri('POST', webhook.url)
        emit_webhooks(webhook.organization, webhook.project, WebhookAction.PROJECT_CREATED, {'data': 'test'})
 
    request_history = m.request_history
    assert len(request_history) == 1
    assert request_history[0].method == 'POST'
    assert request_history[0].url == webhook.url
    TestCase().assertDictEqual(request_history[0].json(), {'action': WebhookAction.PROJECT_CREATED, 'data': 'test'})
 
 
@pytest.mark.django_db
def test_emit_webhooks_for_instance(setup_project_dialog, organization_webhook):
    webhook = organization_webhook
    project_title = 'Projects 1'
    project = Project.objects.create(title=project_title)
    with requests_mock.Mocker(real_http=True) as m:
        m.register_uri('POST', webhook.url)
        emit_webhooks_for_instance(
            webhook.organization, webhook.project, WebhookAction.PROJECT_CREATED, instance=project
        )
    assert len(m.request_history) == 1
    assert m.request_history[0].method == 'POST'
    data = m.request_history[0].json()
    assert 'action' in data
    assert 'project' in data
    assert project_title == data['project']['title']
 
 
@pytest.mark.django_db
def test_exception_catch(organization_webhook):
    webhook = organization_webhook
    with requests_mock.Mocker(real_http=True) as m:
        m.register_uri('POST', webhook.url, exc=requests.exceptions.ConnectTimeout)
        result = run_webhook(webhook, WebhookAction.PROJECT_CREATED)
    assert result is None
 
 
# PROJECT CREATE/UPDATE/DELETE API
@pytest.mark.django_db
def test_webhooks_for_projects(configured_project, business_client, organization_webhook):
    webhook = organization_webhook
 
    # create/update/delete project through API
    # PROJECT_CREATED
    with requests_mock.Mocker(real_http=True) as m:
        m.register_uri('POST', webhook.url)
        response = business_client.post(reverse('projects:api:project-list'))
 
    assert response.status_code == 201
    assert len(list(filter(lambda x: x.url == webhook.url, m.request_history))) == 1
 
    r = list(filter(lambda x: x.url == webhook.url, m.request_history))[0]
    assert r.json()['action'] == WebhookAction.PROJECT_CREATED
 
    project_id = response.json()['id']
    # PROJECT_UPDATED
    with requests_mock.Mocker(real_http=True) as m:
        m.register_uri('POST', webhook.url)
        response = business_client.patch(
            reverse('projects:api:project-detail', kwargs={'pk': project_id}),
            data=json.dumps({'title': 'Test title'}),
            content_type='application/json',
        )
 
    assert response.status_code == 200
    assert len(list(filter(lambda x: x.url == webhook.url, m.request_history))) == 1
 
    r = list(filter(lambda x: x.url == webhook.url, m.request_history))[0]
    assert r.json()['action'] == WebhookAction.PROJECT_UPDATED
    assert r.json()['project']['title'] == 'Test title'
 
    # PROJECT_DELETED
    with requests_mock.Mocker(real_http=True) as m:
        m.register_uri('POST', webhook.url)
        response = business_client.delete(
            reverse('projects:api:project-detail', kwargs={'pk': project_id}),
        )
    assert response.status_code == 204
    assert len(list(filter(lambda x: x.url == organization_webhook.url, m.request_history))) == 1
 
    r = list(filter(lambda x: x.url == organization_webhook.url, m.request_history))[0]
    assert r.json()['action'] == WebhookAction.PROJECT_DELETED
    assert r.json()['project']['id'] == project_id
 
 
# TASK CREATE/DELETE API
# WE DON'T SUPPORT UPDATE FOR TASK
@pytest.mark.django_db
def test_webhooks_for_tasks(configured_project, business_client, organization_webhook):
    webhook = organization_webhook
    # CREATE
    with requests_mock.Mocker(real_http=True) as m:
        m.register_uri('POST', webhook.url)
        response = business_client.post(
            reverse('tasks:api:task-list'),
            data=json.dumps(
                {
                    'project': configured_project.id,
                    'data': {'meta_info': 'meta info A', 'text': 'text A'},
                }
            ),
            content_type='application/json',
        )
    assert response.status_code == 201
    assert len(list(filter(lambda x: x.url == webhook.url, m.request_history))) == 1
 
    r = list(filter(lambda x: x.url == webhook.url, m.request_history))[0]
    assert r.json()['action'] == WebhookAction.TASKS_CREATED
    assert 'tasks' in r.json()
    assert 'project' in r.json()
 
    # DELETE
    task_id = response.json()['id']
    url = webhook.url
    with requests_mock.Mocker(real_http=True) as m:
        m.register_uri('POST', url)
        response = business_client.delete(reverse('tasks:api:task-detail', kwargs={'pk': task_id}))
 
    assert response.status_code == 204
    assert len(list(filter(lambda x: x.url == webhook.url, m.request_history))) == 1
 
    r = list(filter(lambda x: x.url == webhook.url, m.request_history))[0]
    assert r.json()['action'] == WebhookAction.TASKS_DELETED
    assert 'tasks' in r.json()
    assert 'project' in r.json()
 
 
# TASK CREATE on IMPORT
@pytest.mark.django_db
def test_webhooks_for_tasks_import(configured_project, business_client, organization_webhook):
    from django.core.files.uploadedfile import SimpleUploadedFile
 
    webhook = organization_webhook
 
    IMPORT_CSV = 'tests/test_suites/samples/test_5.csv'
 
    with open(IMPORT_CSV, 'rb') as file_:
        data = SimpleUploadedFile('test_5.csv', file_.read(), content_type='multipart/form-data')
    with requests_mock.Mocker(real_http=True) as m:
        m.register_uri('POST', webhook.url)
        response = business_client.post(
            f'/api/projects/{configured_project.id}/import',
            data={'csv_1': data},
            format='multipart',
        )
    assert response.status_code == 201
    assert response.json()['task_count'] == 3
 
    assert len(list(filter(lambda x: x.url == webhook.url, m.request_history))) == 1
 
    r = list(filter(lambda x: x.url == webhook.url, m.request_history))[0]
    assert r.json()['action'] == WebhookAction.TASKS_CREATED
    assert 'tasks' in r.json()
    assert 'project' in r.json()
    assert len(r.json()['tasks']) == response.json()['task_count'] == 3
 
 
# ANNOTATION CREATE/UPDATE/DELETE
@pytest.mark.django_db
def test_webhooks_for_annotation(configured_project, business_client, organization_webhook):
 
    webhook = organization_webhook
    task = configured_project.tasks.all().first()
    # CREATE
    with requests_mock.Mocker(real_http=True) as m:
        m.register_uri('POST', webhook.url)
        response = business_client.post(
            f'/api/tasks/{task.id}/annotations?project={configured_project.id}',
            data=json.dumps(
                {
                    'result': [
                        {
                            'value': {'choices': ['class_A']},
                            'id': 'nJS76J03pi',
                            'from_name': 'text_class',
                            'to_name': 'text',
                            'type': 'choices',
                            'origin': 'manual',
                        }
                    ],
                    'draft_id': 0,
                    'parent_prediction': None,
                    'parent_annotation': None,
                    'project': configured_project.id,
                }
            ),
            content_type='application/json',
        )
 
    assert response.status_code == 201
    assert len(list(filter(lambda x: x.url == webhook.url, m.request_history))) == 1
 
    r = list(filter(lambda x: x.url == webhook.url, m.request_history))[0]
    assert r.json()['action'] == WebhookAction.ANNOTATION_CREATED
    annotation_id = response.json()['id']
 
    # UPDATE POST
    with requests_mock.Mocker(real_http=True) as m:
        m.register_uri('POST', webhook.url)
        response = business_client.put(
            f'/api/annotations/{annotation_id}?project={configured_project.id}&taskId={task.id}',
            data=json.dumps(
                {
                    'result': [],
                }
            ),
            content_type='application/json',
        )
        assert response.status_code == 200
 
        response = business_client.patch(
            f'/api/annotations/{annotation_id}?project={configured_project.id}&taskId={task.id}',
            data=json.dumps(
                {
                    'result': [
                        {
                            'value': {'choices': ['class_B']},
                            'id': 'nJS76J03pi',
                            'from_name': 'text_class',
                            'to_name': 'text',
                            'type': 'choices',
                            'origin': 'manual',
                        }
                    ],
                }
            ),
            content_type='application/json',
        )
        assert response.status_code == 200
 
    assert len(list(filter(lambda x: x.url == webhook.url, m.request_history))) == 2
 
    for r in list(filter(lambda x: x.url == webhook.url, m.request_history)):
        assert r.json()['action'] == WebhookAction.ANNOTATION_UPDATED
 
        assert 'task' in r.json()
        assert 'annotation' in r.json()
        assert 'project' in r.json()
 
    # DELETE
    with requests_mock.Mocker(real_http=True) as m:
        m.register_uri('POST', webhook.url)
        response = business_client.delete(
            f'/api/annotations/{annotation_id}',
            content_type='application/json',
        )
    assert response.status_code == 204
    assert len(list(filter(lambda x: x.url == webhook.url, m.request_history))) == 1
 
    r = list(filter(lambda x: x.url == webhook.url, m.request_history))[0]
    assert r.json()['action'] == WebhookAction.ANNOTATIONS_DELETED
    assert 'annotations' in r.json()
    assert annotation_id == r.json()['annotations'][0]['id']
 
 
# ACTION: DELETE ANNOTATIONS
@pytest.mark.django_db
def test_webhooks_for_action_delete_tasks_annotations(configured_project, business_client, organization_webhook):
    webhook = organization_webhook
 
    # create annotations for tasks
    for task in configured_project.tasks.all():
        response = business_client.post(
            f'/api/tasks/{task.id}/annotations?project={configured_project.id}',
            data=json.dumps({'result': [{'value': {'choices': ['class_B']}}]}),
            content_type='application/json',
        )
        assert response.status_code == 201
 
    with requests_mock.Mocker(real_http=True) as m:
        m.register_uri('POST', webhook.url)
        response = business_client.post(
            f'/api/dm/actions?id=delete_tasks_annotations&project={configured_project.id}',
            data=json.dumps(
                {
                    'project': str(configured_project.id),
                    'selectedItems': {'all': True},
                }
            ),
            content_type='application/json',
        )
 
    assert response.status_code == 200
    assert len(list(filter(lambda x: x.url == webhook.url, m.request_history))) == 1
 
    r = list(filter(lambda x: x.url == webhook.url, m.request_history))[0]
    assert r.json()['action'] == WebhookAction.ANNOTATIONS_DELETED
 
 
# ACTION: DELETE TASKS
@pytest.mark.django_db
def test_webhooks_for_action_delete_tasks(configured_project, business_client, organization_webhook):
    webhook = organization_webhook
    with requests_mock.Mocker(real_http=True) as m:
        m.register_uri('POST', webhook.url)
        response = business_client.post(
            f'/api/dm/actions?id=delete_tasks&project={configured_project.id}',
            data=json.dumps(
                {
                    'project': str(configured_project.id),
                    'selectedItems': {'all': True},
                }
            ),
            content_type='application/json',
        )
    assert response.status_code == 200
    assert len(list(filter(lambda x: x.url == webhook.url, m.request_history))) == 1
 
    r = list(filter(lambda x: x.url == webhook.url, m.request_history))[0]
    assert r.json()['action'] == WebhookAction.TASKS_DELETED
 
 
# CREATE TASKS FROM STORAGES
@pytest.mark.django_db
def test_webhooks_for_tasks_from_storages(configured_project, business_client, organization_webhook):
    webhook = organization_webhook
    # CREATE
    with requests_mock.Mocker(real_http=True) as m:
        m.register_uri('POST', webhook.url)
        add_url = '/api/storages/s3'
        payload = {
            'bucket': 'pytest-s3-images',
            'project': configured_project.id,
            'title': 'Testing S3 storage (bucket from conftest.py)',
            'use_blob_urls': True,
            'presign_ttl': 3600,
        }
        add_response = business_client.post(add_url, data=json.dumps(payload), content_type='application/json')
        storage_pk = add_response.json()['id']
 
        # Sync S3 Storage
        sync_url = f'/api/storages/s3/{storage_pk}/sync'
        business_client.post(sync_url)
    # assert response.status_code == 201
    assert len(list(filter(lambda x: x.url == webhook.url, m.request_history))) == 1
 
    r = list(filter(lambda x: x.url == webhook.url, m.request_history))[0]
    assert r.json()['action'] == WebhookAction.TASKS_CREATED
    assert 'tasks' in r.json()
    assert 'project' in r.json()
 
 
@pytest.mark.django_db
def test_start_training_webhook(setup_project_dialog, ml_start_training_webhook, business_client):
    """
    1. Setup: The test uses the project_webhook fixture, which assumes that a webhook
    is already configured for the project.
    2. Mocking the POST Request: The requests_mock.Mocker is used to mock
    the POST request to the webhook URL. This is where you expect the START_TRAINING action to be sent.
    3. Making the Request: The test makes a POST request to the /api/ml/{id}/train endpoint.
 
    Assertions:
        - The response status code is checked to ensure the request was successful.
        - It verifies that exactly one request was made to the webhook URL.
        - It checks that the request method was POST.
        - The request URL and the JSON payload are validated against expected values.
    """
    from ml.models import MLBackend
 
    webhook = ml_start_training_webhook
    project = webhook.project
    ml = MLBackend.objects.create(project=project, url='http://0.0.0.0:9090')
 
    # Mock the POST request to the ML backend train endpoint
    with requests_mock.Mocker(real_http=True) as m:
        m.register_uri('POST', webhook.url)
        response = business_client.post(
            f'/api/ml/{ml.id}/train',
            data=json.dumps({'action': 'START_TRAINING'}),
            content_type='application/json',
        )
 
    assert response.status_code == 200
    request_history = m.request_history
    assert len(request_history) == 1
    assert request_history[0].method == 'POST'
    assert request_history[0].url == webhook.url
    assert 'project' in request_history[0].json()
    assert request_history[0].json()['action'] == 'START_TRAINING'
 
 
@pytest.mark.django_db
def test_webhook_batching_with_feature_flag(configured_project, organization_webhook):
    """Test that webhooks are sent in batches when feature flag is enabled."""
    from unittest.mock import patch
 
    from django.conf import settings
    from tasks.models import Task
    from webhooks.utils import emit_webhooks_for_instance_sync
 
    webhook = organization_webhook
    project = configured_project
 
    # Create multiple tasks to test batching
    tasks = []
    for i in range(250):  # Create more than WEBHOOK_BATCH_SIZE
        task = Task.objects.create(data={'text': f'Test task {i}'}, project=project)
        tasks.append(task)
 
    # Test with feature flag enabled
    with patch('webhooks.utils.flag_set') as mock_flag_set:
        mock_flag_set.return_value = True
 
        with requests_mock.Mocker(real_http=True) as m:
            m.register_uri('POST', webhook.url)
 
            # Set batch size to 100 for testing
            original_batch_size = getattr(settings, 'WEBHOOK_BATCH_SIZE', 100)
            settings.WEBHOOK_BATCH_SIZE = 100
 
            try:
                emit_webhooks_for_instance_sync(
                    webhook.organization, webhook.project, WebhookAction.TASKS_CREATED, instance=tasks
                )
 
                # Should have 3 requests (250 tasks / 100 batch size = 3 batches)
                webhook_requests = list(filter(lambda x: x.url == webhook.url, m.request_history))
                assert len(webhook_requests) == 3
 
                # Check first batch has 100 tasks
                first_batch = webhook_requests[0].json()
                assert 'tasks' in first_batch
                assert len(first_batch['tasks']) == 100
 
                # Check second batch has 100 tasks
                second_batch = webhook_requests[1].json()
                assert len(second_batch['tasks']) == 100
 
                # Check third batch has 50 tasks (remaining)
                third_batch = webhook_requests[2].json()
                assert len(third_batch['tasks']) == 50
 
            finally:
                settings.WEBHOOK_BATCH_SIZE = original_batch_size
 
 
@pytest.mark.django_db
def test_webhook_no_batching_without_feature_flag(configured_project, organization_webhook):
    """Test that webhooks are sent in single request when feature flag is disabled."""
    from unittest.mock import patch
 
    from tasks.models import Task
    from webhooks.utils import emit_webhooks_for_instance_sync
 
    webhook = organization_webhook
    project = configured_project
 
    # Create multiple tasks
    tasks = []
    for i in range(150):
        task = Task.objects.create(data={'text': f'Test task {i}'}, project=project)
        tasks.append(task)
 
    # Test with feature flag disabled
    with patch('webhooks.utils.flag_set') as mock_flag_set:
        mock_flag_set.return_value = False
 
        with requests_mock.Mocker(real_http=True) as m:
            m.register_uri('POST', webhook.url)
 
            emit_webhooks_for_instance_sync(
                webhook.organization, webhook.project, WebhookAction.TASKS_CREATED, instance=tasks
            )
 
            # Should have only 1 request (no batching)
            webhook_requests = list(filter(lambda x: x.url == webhook.url, m.request_history))
            assert len(webhook_requests) == 1
 
            # Check all 150 tasks are in single request
            request_data = webhook_requests[0].json()
            assert 'tasks' in request_data
            assert len(request_data['tasks']) == 150