Bin
2025-12-16 971a2a12c03b74dd2d7d668b9dbc599f5131bcaf
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
import pytest
from django.contrib.auth import get_user_model
from label_studio_sdk import LabelStudio
from organizations.tests.factories import OrganizationFactory
from projects.tests.factories import ProjectFactory
from tasks.tests.factories import TaskFactory
from users.tests.factories import UserFactory
 
User = get_user_model()
 
 
class TestSDKPredictionValidation:
    """Comprehensive tests for prediction validation using Label Studio SDK"""
 
    @pytest.fixture(autouse=True)
    def setup(self, django_db_setup, django_db_blocker):
        """Set up test environment with user, organization, project, and task using factories"""
        with django_db_blocker.unblock():
            self.user = UserFactory()
            self.organization = OrganizationFactory(created_by=self.user)
            self.user.active_organization = self.organization
            self.user.save()
 
            # Create a project with a comprehensive label configuration
            self.project = ProjectFactory(
                title='Test Project',
                label_config="""
                <View>
                  <Text name="text" value="$text"/>
                  <Choices name="sentiment" toName="text">
                    <Choice value="positive"/>
                    <Choice value="negative"/>
                    <Choice value="neutral"/>
                  </Choices>
                  <Labels name="entities" toName="text">
                    <Label value="person" background="red"/>
                    <Label value="organization" background="blue"/>
                    <Label value="location" background="green"/>
                  </Labels>
                  <Rating name="quality" toName="text">
                    <Choice value="1"/>
                    <Choice value="2"/>
                    <Choice value="3"/>
                    <Choice value="4"/>
                    <Choice value="5"/>
                  </Rating>
                  <TextArea name="summary" toName="text"/>
                </View>
                """,
                created_by=self.user,
                organization=self.organization,
            )
 
            # Create a task
            self.task = TaskFactory(project=self.project, data={'text': 'John Smith works at Microsoft in Seattle.'})
 
    def test_valid_prediction_choices(self, django_live_url, business_client):
        """Test creating a valid prediction with choices using SDK"""
        ls = LabelStudio(base_url=django_live_url, api_key=business_client.api_key)
 
        prediction_data = {
            'task': self.task.id,
            'result': [
                {'from_name': 'sentiment', 'to_name': 'text', 'type': 'choices', 'value': {'choices': ['positive']}}
            ],
            'score': 0.95,
            'model_version': 'v1.0',
        }
 
        # Use the SDK to create prediction
        prediction = ls.predictions.create(**prediction_data)
 
        # Verify the prediction was created successfully
        assert prediction.id is not None
        assert prediction.task == self.task.id
        assert prediction.result == prediction_data['result']
 
    def test_valid_prediction_labels(self, django_live_url, business_client):
        """Test creating a valid prediction with labels using SDK"""
        ls = LabelStudio(base_url=django_live_url, api_key=business_client.api_key)
 
        prediction_data = {
            'task': self.task.id,
            'result': [
                {
                    'from_name': 'entities',
                    'to_name': 'text',
                    'type': 'labels',
                    'value': {'labels': ['person'], 'start': 0, 'end': 10, 'text': 'John Smith'},
                }
            ],
            'score': 0.85,
            'model_version': 'v1.0',
        }
 
        prediction = ls.predictions.create(**prediction_data)
 
        assert prediction.id is not None
        assert prediction.task == self.task.id
        assert prediction.result == prediction_data['result']
 
    def test_valid_prediction_rating(self, django_live_url, business_client):
        """Test creating a valid prediction with rating using SDK"""
        ls = LabelStudio(base_url=django_live_url, api_key=business_client.api_key)
 
        prediction_data = {
            'task': self.task.id,
            'result': [{'from_name': 'quality', 'to_name': 'text', 'type': 'rating', 'value': {'rating': 4}}],
            'score': 0.90,
            'model_version': 'v1.0',
        }
 
        prediction = ls.predictions.create(**prediction_data)
 
        assert prediction.id is not None
        assert prediction.task == self.task.id
        assert prediction.result == prediction_data['result']
 
    def test_valid_prediction_textarea(self, django_live_url, business_client):
        """Test creating a valid prediction with textarea using SDK"""
        ls = LabelStudio(base_url=django_live_url, api_key=business_client.api_key)
 
        prediction_data = {
            'task': self.task.id,
            'result': [
                {
                    'from_name': 'summary',
                    'to_name': 'text',
                    'type': 'textarea',
                    'value': {'text': ['This is a summary of the text.']},
                }
            ],
            'score': 0.88,
            'model_version': 'v1.0',
        }
 
        prediction = ls.predictions.create(**prediction_data)
 
        assert prediction.id is not None
        assert prediction.task == self.task.id
        assert prediction.result == prediction_data['result']
 
    def test_missing_required_fields(self, django_live_url, business_client):
        """Test prediction with missing required fields using SDK"""
        ls = LabelStudio(base_url=django_live_url, api_key=business_client.api_key)
 
        prediction_data = {
            'task': self.task.id,
            'result': [
                {
                    'from_name': 'sentiment',
                    # Missing 'to_name', 'type', 'value'
                }
            ],
            'score': 0.95,
            'model_version': 'v1.0',
        }
 
        # This should fail validation
        with pytest.raises(Exception):
            ls.predictions.create(**prediction_data)
 
    def test_invalid_from_name(self, django_live_url, business_client):
        """Test prediction with non-existent from_name using SDK"""
        ls = LabelStudio(base_url=django_live_url, api_key=business_client.api_key)
 
        prediction_data = {
            'task': self.task.id,
            'result': [
                {
                    'from_name': 'nonexistent_tag',
                    'to_name': 'text',
                    'type': 'choices',
                    'value': {'choices': ['positive']},
                }
            ],
            'score': 0.95,
            'model_version': 'v1.0',
        }
 
        # This should fail validation
        with pytest.raises(Exception):
            ls.predictions.create(**prediction_data)
 
    def test_invalid_to_name(self, django_live_url, business_client):
        """Test prediction with non-existent to_name using SDK"""
        ls = LabelStudio(base_url=django_live_url, api_key=business_client.api_key)
 
        prediction_data = {
            'task': self.task.id,
            'result': [
                {
                    'from_name': 'sentiment',
                    'to_name': 'nonexistent_target',
                    'type': 'choices',
                    'value': {'choices': ['positive']},
                }
            ],
            'score': 0.95,
            'model_version': 'v1.0',
        }
 
        # This should fail validation
        with pytest.raises(Exception):
            ls.predictions.create(**prediction_data)
 
    def test_type_mismatch(self, django_live_url, business_client):
        """Test prediction with type mismatch using SDK"""
        ls = LabelStudio(base_url=django_live_url, api_key=business_client.api_key)
 
        prediction_data = {
            'task': self.task.id,
            'result': [
                {
                    'from_name': 'sentiment',
                    'to_name': 'text',
                    'type': 'labels',  # Wrong type - should be 'choices'
                    'value': {'choices': ['positive']},
                }
            ],
            'score': 0.95,
            'model_version': 'v1.0',
        }
 
        # This should fail validation
        with pytest.raises(Exception):
            ls.predictions.create(**prediction_data)
 
    def test_invalid_choice_value(self, django_live_url, business_client):
        """Test prediction with invalid choice value using SDK"""
        ls = LabelStudio(base_url=django_live_url, api_key=business_client.api_key)
 
        prediction_data = {
            'task': self.task.id,
            'result': [
                {
                    'from_name': 'sentiment',
                    'to_name': 'text',
                    'type': 'choices',
                    'value': {'choices': ['invalid_choice']},  # Not in available choices
                }
            ],
            'score': 0.95,
            'model_version': 'v1.0',
        }
 
        # This should fail validation
        with pytest.raises(Exception):
            ls.predictions.create(**prediction_data)
 
    def test_invalid_rating_value(self, django_live_url, business_client):
        """Test prediction with invalid rating value using SDK"""
        ls = LabelStudio(base_url=django_live_url, api_key=business_client.api_key)
 
        prediction_data = {
            'task': self.task.id,
            'result': [
                {
                    'from_name': 'quality',
                    'to_name': 'text',
                    'type': 'rating',
                    'value': {'rating': 6},  # Rating should be 1-5
                }
            ],
            'score': 0.90,
            'model_version': 'v1.0',
        }
 
        # This should fail validation
        with pytest.raises(Exception):
            ls.predictions.create(**prediction_data)
 
    def test_invalid_labels_value(self, django_live_url, business_client):
        """Test prediction with invalid labels value using SDK"""
        ls = LabelStudio(base_url=django_live_url, api_key=business_client.api_key)
 
        prediction_data = {
            'task': self.task.id,
            'result': [
                {
                    'from_name': 'entities',
                    'to_name': 'text',
                    'type': 'labels',
                    'value': {
                        'labels': ['invalid_label'],  # Not in available labels
                        'start': 0,
                        'end': 10,
                        'text': 'John Smith',
                    },
                }
            ],
            'score': 0.85,
            'model_version': 'v1.0',
        }
 
        # This should fail validation
        with pytest.raises(Exception):
            ls.predictions.create(**prediction_data)
 
    def test_missing_value_field(self, django_live_url, business_client):
        """Test prediction with missing value field using SDK"""
        ls = LabelStudio(base_url=django_live_url, api_key=business_client.api_key)
 
        prediction_data = {
            'task': self.task.id,
            'result': [
                {
                    'from_name': 'sentiment',
                    'to_name': 'text',
                    'type': 'choices'
                    # Missing 'value' field
                }
            ],
            'score': 0.95,
            'model_version': 'v1.0',
        }
 
        # This should fail validation
        with pytest.raises(Exception):
            ls.predictions.create(**prediction_data)
 
    def test_empty_result_array(self, django_live_url, business_client):
        """Test prediction with empty result array using SDK"""
        ls = LabelStudio(base_url=django_live_url, api_key=business_client.api_key)
 
        prediction_data = {'task': self.task.id, 'result': [], 'score': 0.95, 'model_version': 'v1.0'}  # Empty array
 
        prediction = ls.predictions.create(**prediction_data)
        assert prediction.id is not None
        assert prediction.task == self.task.id
        assert prediction.result == prediction_data['result']
 
    def test_multiple_regions_mixed_validity(self, django_live_url, business_client):
        """Test prediction with multiple regions where some are valid and some are invalid using SDK"""
        ls = LabelStudio(base_url=django_live_url, api_key=business_client.api_key)
 
        prediction_data = {
            'task': self.task.id,
            'result': [
                {'from_name': 'sentiment', 'to_name': 'text', 'type': 'choices', 'value': {'choices': ['positive']}},
                {
                    'from_name': 'entities',
                    'to_name': 'text',
                    'type': 'labels',
                    'value': {'labels': [['person']], 'start': 0, 'end': 10, 'text': 'John Smith'},
                },
                {
                    'from_name': 'nonexistent_tag',  # Invalid
                    'to_name': 'text',
                    'type': 'choices',
                    'value': {'choices': ['positive']},
                },
            ],
            'score': 0.85,
            'model_version': 'v1.0',
        }
 
        # This should fail validation due to the invalid region
        with pytest.raises(Exception):
            ls.predictions.create(**prediction_data)
 
    def test_complex_valid_prediction(self, django_live_url, business_client):
        """Test a complex valid prediction with multiple regions using SDK"""
        ls = LabelStudio(base_url=django_live_url, api_key=business_client.api_key)
 
        prediction_data = {
            'task': self.task.id,
            'result': [
                {'from_name': 'sentiment', 'to_name': 'text', 'type': 'choices', 'value': {'choices': ['positive']}},
                {
                    'from_name': 'entities',
                    'to_name': 'text',
                    'type': 'labels',
                    'value': {'labels': ['person'], 'start': 0, 'end': 10, 'text': 'John Smith'},
                },
                {
                    'from_name': 'entities',
                    'to_name': 'text',
                    'type': 'labels',
                    'value': {'labels': ['organization'], 'start': 17, 'end': 26, 'text': 'Microsoft'},
                },
                {'from_name': 'quality', 'to_name': 'text', 'type': 'rating', 'value': {'rating': 4}},
                {
                    'from_name': 'summary',
                    'to_name': 'text',
                    'type': 'textarea',
                    'value': {'text': ['A person works at an organization.']},
                },
            ],
            'score': 0.92,
            'model_version': 'v2.0',
        }
 
        prediction = ls.predictions.create(**prediction_data)
 
        assert prediction.id is not None
        assert prediction.task == self.task.id
        assert prediction.result == prediction_data['result']
 
    def test_invalid_textarea_value(self, django_live_url, business_client):
        """Test prediction with invalid textarea value structure using SDK"""
        ls = LabelStudio(base_url=django_live_url, api_key=business_client.api_key)
 
        prediction_data = {
            'task': self.task.id,
            'result': [
                {
                    'from_name': 'summary',
                    'to_name': 'text',
                    'type': 'textarea',
                    'value': {'text': 'This should be a list'},  # Should be list, not string
                }
            ],
            'score': 0.88,
            'model_version': 'v1.0',
        }
 
        # This should fail validation
        with pytest.raises(Exception):
            ls.predictions.create(**prediction_data)
 
    def test_invalid_labels_structure(self, django_live_url, business_client):
        """Test prediction with invalid labels structure using SDK"""
        ls = LabelStudio(base_url=django_live_url, api_key=business_client.api_key)
 
        prediction_data = {
            'task': self.task.id,
            'result': [
                {
                    'from_name': 'entities',
                    'to_name': 'text',
                    'type': 'labels',
                    'value': {
                        'labels': 'person',  # Should be list of lists
                        'start': 0,
                        'end': 10,
                        'text': 'John Smith',
                    },
                }
            ],
            'score': 0.85,
            'model_version': 'v1.0',
        }
 
        # This should fail validation
        with pytest.raises(Exception):
            ls.predictions.create(**prediction_data)
 
    def test_missing_text_in_labels(self, django_live_url, business_client):
        """Test prediction with missing text field in labels using SDK"""
        ls = LabelStudio(base_url=django_live_url, api_key=business_client.api_key)
 
        prediction_data = {
            'task': self.task.id,
            'result': [
                {
                    'from_name': 'entities',
                    'to_name': 'text',
                    'type': 'labels',
                    'value': {
                        'labels': [['person']],
                        'start': 0,
                        'end': 10
                        # Missing 'text' field
                    },
                }
            ],
            'score': 0.85,
            'model_version': 'v1.0',
        }
 
        # This should fail validation
        with pytest.raises(Exception):
            ls.predictions.create(**prediction_data)
 
    def test_invalid_start_end_positions(self, django_live_url, business_client):
        """Test prediction with invalid start/end positions using SDK"""
        ls = LabelStudio(base_url=django_live_url, api_key=business_client.api_key)
 
        prediction_data = {
            'task': self.task.id,
            'result': [
                {
                    'from_name': 'entities',
                    'to_name': 'text',
                    'type': 'labels',
                    'value': {
                        'labels': [['person']],
                        'start': 100,  # Beyond text length
                        'end': 110,
                        'text': 'John Smith',
                    },
                }
            ],
            'score': 0.85,
            'model_version': 'v1.0',
        }
 
        # This should fail validation
        with pytest.raises(Exception):
            ls.predictions.create(**prediction_data)
 
    def test_end_before_start(self, django_live_url, business_client):
        """Test prediction with end position before start position using SDK"""
        ls = LabelStudio(base_url=django_live_url, api_key=business_client.api_key)
 
        prediction_data = {
            'task': self.task.id,
            'result': [
                {
                    'from_name': 'entities',
                    'to_name': 'text',
                    'type': 'labels',
                    'value': {'labels': [['person']], 'start': 10, 'end': 5, 'text': 'John Smith'},  # End before start
                }
            ],
            'score': 0.85,
            'model_version': 'v1.0',
        }
 
        # This should fail validation
        with pytest.raises(Exception):
            ls.predictions.create(**prediction_data)