-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtest_structured.py
More file actions
932 lines (717 loc) · 30.1 KB
/
test_structured.py
File metadata and controls
932 lines (717 loc) · 30.1 KB
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
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
"""Tests for l0.structured module."""
from collections.abc import AsyncIterator
from typing import Any
import pytest
from pydantic import BaseModel, ValidationError
from l0._structured import (
AutoCorrectInfo,
StructuredResult,
StructuredState,
StructuredTelemetry,
structured,
structured_array,
structured_object,
structured_stream,
)
from l0.adapters import AdaptedEvent, Adapters
from l0.events import ObservabilityEventType
from l0.types import Event, EventType, Retry, Timeout
# Test adapter that passes through Event objects
class PassthroughAdapter:
"""Test adapter that passes through Event objects directly."""
name = "passthrough_structured"
def detect(self, stream: Any) -> bool:
"""Detect async generators (our test streams)."""
return hasattr(stream, "__anext__")
async def wrap(
self, stream: Any, options: Any = None
) -> AsyncIterator[AdaptedEvent[Any]]:
"""Pass through events wrapped in AdaptedEvent."""
async for event in stream:
yield AdaptedEvent(event=event, raw_chunk=None)
@pytest.fixture(autouse=True)
def register_passthrough_adapter():
"""Register and cleanup the passthrough adapter for tests."""
Adapters.register(PassthroughAdapter())
yield
Adapters.reset()
class UserProfile(BaseModel):
name: str
age: int
email: str
class SimpleModel(BaseModel):
value: str
class TestStructured:
@pytest.mark.asyncio
async def test_structured_parses_json(self):
"""Test that structured parses valid JSON."""
async def json_stream():
yield Event(
type=EventType.TOKEN,
text='{"name": "John", "age": 30, "email": "john@example.com"}',
)
yield Event(type=EventType.COMPLETE)
result = await structured(
schema=UserProfile,
stream=json_stream,
)
assert isinstance(result, StructuredResult)
assert result.data.name == "John"
assert result.data.age == 30
assert result.data.email == "john@example.com"
assert result.raw is not None
@pytest.mark.asyncio
async def test_structured_extracts_from_markdown(self):
"""Test that structured extracts JSON from markdown."""
async def markdown_stream():
yield Event(
type=EventType.TOKEN,
text='Here is the data:\n```json\n{"value": "test"}\n```',
)
yield Event(type=EventType.COMPLETE)
result = await structured(
schema=SimpleModel,
stream=markdown_stream,
)
assert result.data.value == "test"
@pytest.mark.asyncio
async def test_structured_auto_corrects_json(self):
"""Test that structured auto-corrects malformed JSON."""
async def malformed_stream():
# Missing closing brace
yield Event(type=EventType.TOKEN, text='{"value": "test"')
yield Event(type=EventType.COMPLETE)
result = await structured(
schema=SimpleModel,
stream=malformed_stream,
auto_correct=True,
)
assert result.data.value == "test"
assert result.corrected is True
assert len(result.corrections) > 0
@pytest.mark.asyncio
async def test_structured_raises_on_invalid(self):
"""Test that structured raises on invalid JSON."""
async def invalid_stream():
yield Event(type=EventType.TOKEN, text='{"wrong_field": "value"}')
yield Event(type=EventType.COMPLETE)
with pytest.raises(ValueError, match="Schema validation failed"):
await structured(
schema=UserProfile,
stream=invalid_stream,
)
@pytest.mark.asyncio
async def test_structured_reraises_non_validation_errors(self):
"""Test that non-validation errors are re-raised as-is."""
class CustomError(Exception):
pass
async def failing_stream():
raise CustomError("Something went wrong")
yield # Make it a generator # noqa: B030
with pytest.raises(CustomError, match="Something went wrong"):
await structured(
schema=UserProfile,
stream=failing_stream,
)
@pytest.mark.asyncio
async def test_structured_without_auto_correct(self):
"""Test structured with auto_correct disabled."""
async def valid_stream():
yield Event(type=EventType.TOKEN, text='{"value": "test"}')
yield Event(type=EventType.COMPLETE)
result = await structured(
schema=SimpleModel,
stream=valid_stream,
auto_correct=False,
)
assert result.data.value == "test"
assert result.corrected is False
@pytest.mark.asyncio
async def test_structured_accumulates_tokens(self):
"""Test that structured accumulates multiple tokens."""
async def multi_token_stream():
yield Event(type=EventType.TOKEN, text='{"value":')
yield Event(type=EventType.TOKEN, text=' "hello')
yield Event(type=EventType.TOKEN, text=' world"}')
yield Event(type=EventType.COMPLETE)
result = await structured(
schema=SimpleModel,
stream=multi_token_stream,
)
assert result.data.value == "hello world"
@pytest.mark.asyncio
async def test_structured_on_auto_correct_callback(self):
"""Test on_auto_correct callback is called."""
callback_called = False
callback_info = None
def on_auto_correct(info: AutoCorrectInfo):
nonlocal callback_called, callback_info
callback_called = True
callback_info = info
async def malformed_stream():
yield Event(type=EventType.TOKEN, text='{"value": "test",}')
yield Event(type=EventType.COMPLETE)
result = await structured(
schema=SimpleModel,
stream=malformed_stream,
auto_correct=True,
on_auto_correct=on_auto_correct,
)
assert result.data.value == "test"
assert callback_called
assert callback_info is not None
assert len(callback_info.corrections) > 0
@pytest.mark.asyncio
async def test_structured_on_validation_error_callback(self):
"""Test on_validation_error callback is called on failures."""
errors_received = []
def on_validation_error(error: ValidationError, attempt: int):
errors_received.append((error, attempt))
async def invalid_stream():
yield Event(type=EventType.TOKEN, text='{"wrong": "field"}')
yield Event(type=EventType.COMPLETE)
with pytest.raises(ValueError):
await structured(
schema=UserProfile,
stream=invalid_stream,
retry=Retry(attempts=2),
on_validation_error=on_validation_error,
)
# Should have been called for each attempt
assert len(errors_received) == 2
assert errors_received[0][1] == 1
assert errors_received[1][1] == 2
@pytest.mark.asyncio
async def test_structured_emits_parse_end_on_validation_failure(self):
"""Test that PARSE_END is emitted even when validation fails."""
events_emitted = []
def on_event(event: Any) -> None:
events_emitted.append(event.type)
async def invalid_stream():
yield Event(type=EventType.TOKEN, text='{"wrong": "field"}')
yield Event(type=EventType.COMPLETE)
with pytest.raises(ValueError):
await structured(
schema=UserProfile,
stream=invalid_stream,
on_event=on_event,
)
# Verify PARSE_START and PARSE_END are both emitted
assert ObservabilityEventType.PARSE_START in events_emitted
assert ObservabilityEventType.PARSE_END in events_emitted
# Verify exactly one SCHEMA_VALIDATION_END (no duplicates)
schema_validation_end_count = events_emitted.count(
ObservabilityEventType.SCHEMA_VALIDATION_END
)
assert schema_validation_end_count == 1
class TestStructuredStream:
"""Test structured_stream() function."""
@pytest.mark.asyncio
async def test_structured_stream_basic(self):
"""Test basic structured streaming."""
async def json_stream():
yield Event(type=EventType.TOKEN, text='{"value":')
yield Event(type=EventType.TOKEN, text=' "streamed"}')
yield Event(type=EventType.COMPLETE)
stream, result_holder = await structured_stream(
schema=SimpleModel,
stream=json_stream,
)
tokens = []
async for event in stream:
if event.is_token and event.text:
tokens.append(event.text)
# Validate after consuming stream
result = await result_holder.validate()
assert result.data.value == "streamed"
assert len(tokens) == 2
@pytest.mark.asyncio
async def test_structured_stream_with_auto_correct(self):
"""Test structured streaming with auto-correction."""
async def malformed_stream():
yield Event(type=EventType.TOKEN, text='{"value": "test"')
yield Event(type=EventType.COMPLETE)
stream, result_holder = await structured_stream(
schema=SimpleModel,
stream=malformed_stream,
auto_correct=True,
)
async for _ in stream:
pass
result = await result_holder.validate()
assert result.data.value == "test"
assert result.corrected is True
@pytest.mark.asyncio
async def test_structured_stream_validate_emits_events(self):
"""Test that validate() emits observability events via on_event callback."""
from l0.events import ObservabilityEventType
events_received = []
def on_event(event: Any) -> None:
events_received.append(event.type)
async def json_stream():
yield Event(type=EventType.TOKEN, text='{"value": "test"}')
yield Event(type=EventType.COMPLETE)
stream, result_holder = await structured_stream(
schema=SimpleModel,
stream=json_stream,
on_event=on_event,
)
async for _ in stream:
pass
# Validate should emit parse/validation events
result = await result_holder.validate()
assert result.data.value == "test"
# Check that validation events were emitted
assert ObservabilityEventType.PARSE_START in events_received
assert ObservabilityEventType.PARSE_END in events_received
@pytest.mark.asyncio
async def test_structured_stream_validate_raises_valueerror(self):
"""Test that validate() raises ValueError, not ValidationError."""
async def invalid_stream():
yield Event(type=EventType.TOKEN, text='{"wrong": "field"}')
yield Event(type=EventType.COMPLETE)
stream, result_holder = await structured_stream(
schema=UserProfile,
stream=invalid_stream,
)
async for _ in stream:
pass
# Should raise ValueError, not pydantic.ValidationError
with pytest.raises(ValueError, match="Schema validation failed"):
await result_holder.validate()
class TestStructuredIteratorValidation:
"""Test validation of async iterator vs factory usage."""
@pytest.mark.asyncio
async def test_direct_iterator_with_retry_auto_buffers(self):
"""Test that direct async iterator is auto-buffered for retries."""
from l0 import Retry
attempt_count = 0
async def json_gen():
nonlocal attempt_count
attempt_count += 1
if attempt_count == 1:
# First attempt returns invalid JSON
yield Event(type=EventType.TOKEN, text='{"wrong": "field"}')
else:
# This won't be reached since we buffer - but validation will retry
yield Event(type=EventType.TOKEN, text='{"value": "test"}')
yield Event(type=EventType.COMPLETE)
# Create a direct async iterator (not a factory)
direct_iterator = json_gen()
# This should work - iterator is auto-buffered
# Note: retries will replay the same buffered content, so validation
# will fail on all attempts with the same invalid JSON
with pytest.raises(ValueError):
await structured(
schema=SimpleModel,
stream=direct_iterator,
retry=Retry(attempts=2),
)
# Iterator was consumed once (buffered), then replayed
assert attempt_count == 1
@pytest.mark.asyncio
async def test_direct_iterator_works_without_retry(self):
"""Test that direct async iterator works fine without retry."""
async def json_gen():
yield Event(type=EventType.TOKEN, text='{"value": "test"}')
yield Event(type=EventType.COMPLETE)
direct_iterator = json_gen()
result = await structured(
schema=SimpleModel,
stream=direct_iterator,
)
assert result.data.value == "test"
@pytest.mark.asyncio
async def test_factory_with_retry_works(self):
"""Test that using a factory function with retry works."""
from l0 import Retry
async def json_gen():
yield Event(type=EventType.TOKEN, text='{"value": "test"}')
yield Event(type=EventType.COMPLETE)
# Pass factory function (not direct iterator)
result = await structured(
schema=SimpleModel,
stream=json_gen, # Factory, not json_gen()
retry=Retry(attempts=2),
)
assert result.data.value == "test"
@pytest.mark.asyncio
async def test_direct_iterator_with_fallback_auto_buffers(self):
"""Test that direct async iterators in fallbacks are also buffered."""
async def failing_gen():
yield Event(type=EventType.TOKEN, text='{"wrong": "field"}')
yield Event(type=EventType.COMPLETE)
async def fallback_gen():
yield Event(type=EventType.TOKEN, text='{"value": "from_fallback"}')
yield Event(type=EventType.COMPLETE)
# Both are direct iterators
direct_main = failing_gen()
direct_fallback = fallback_gen()
result = await structured(
schema=SimpleModel,
stream=direct_main,
fallbacks=[direct_fallback],
)
assert result.data.value == "from_fallback"
class TestStructuredState:
"""Test StructuredState tracking."""
@pytest.mark.asyncio
async def test_structured_state_on_success(self):
"""Test that structured_state is populated on success."""
async def json_stream():
yield Event(type=EventType.TOKEN, text='{"value": "test"}')
yield Event(type=EventType.COMPLETE)
result = await structured(
schema=SimpleModel,
stream=json_stream,
)
assert result.structured_state is not None
assert result.structured_state.validation_failures == 0
assert result.structured_state.validation_time_ms is not None
assert result.structured_state.validation_time_ms >= 0
@pytest.mark.asyncio
async def test_structured_state_tracks_corrections(self):
"""Test that corrections are tracked in structured_state."""
async def json_stream():
yield Event(type=EventType.TOKEN, text='{"value": "test",}')
yield Event(type=EventType.COMPLETE)
result = await structured(
schema=SimpleModel,
stream=json_stream,
auto_correct=True,
)
assert result.structured_state is not None
assert result.structured_state.auto_corrections >= 1
assert len(result.structured_state.correction_types) > 0
class TestStructuredTelemetry:
"""Test StructuredTelemetry when monitoring is enabled."""
@pytest.mark.asyncio
async def test_telemetry_when_monitoring_enabled(self):
"""Test that telemetry is populated when monitoring is enabled."""
async def json_stream():
yield Event(type=EventType.TOKEN, text='{"value": "test"}')
yield Event(type=EventType.COMPLETE)
result = await structured(
schema=SimpleModel,
stream=json_stream,
monitoring=True,
)
assert result.telemetry is not None
assert result.telemetry.schema_name == "SimpleModel"
assert result.telemetry.validation_attempts >= 1
assert result.telemetry.validation_success is True
assert result.telemetry.validation_time_ms is not None
@pytest.mark.asyncio
async def test_telemetry_not_present_when_monitoring_disabled(self):
"""Test that telemetry is None when monitoring is disabled."""
async def json_stream():
yield Event(type=EventType.TOKEN, text='{"value": "test"}')
yield Event(type=EventType.COMPLETE)
result = await structured(
schema=SimpleModel,
stream=json_stream,
monitoring=False,
)
assert result.telemetry is None
class TestStructuredOnRetryCallback:
"""Test on_retry callback."""
@pytest.mark.asyncio
async def test_on_retry_called_on_validation_failure(self):
"""Test that on_retry is called when validation fails."""
retry_calls = []
def on_retry(attempt: int, reason: str):
retry_calls.append((attempt, reason))
async def invalid_stream():
yield Event(type=EventType.TOKEN, text='{"wrong": "field"}')
yield Event(type=EventType.COMPLETE)
with pytest.raises(ValueError):
await structured(
schema=SimpleModel,
stream=invalid_stream,
retry=Retry(attempts=2),
on_retry=on_retry,
)
# Should have been called once (after first failure, before second attempt)
assert len(retry_calls) >= 1
assert retry_calls[0][0] == 1 # First retry attempt
class TestStructuredDetectZeroTokens:
"""Test detect_zero_tokens option."""
@pytest.mark.asyncio
async def test_detect_zero_tokens_raises_on_empty(self):
"""Test that zero-token detection raises error on empty output."""
async def empty_stream():
yield Event(type=EventType.TOKEN, text="")
yield Event(type=EventType.COMPLETE)
with pytest.raises(ValueError, match="Zero-token output"):
await structured(
schema=SimpleModel,
stream=empty_stream,
detect_zero_tokens=True,
)
@pytest.mark.asyncio
async def test_detect_zero_tokens_disabled_by_default(self):
"""Test that zero-token detection is disabled by default."""
async def whitespace_stream():
yield Event(type=EventType.TOKEN, text=" ")
yield Event(type=EventType.COMPLETE)
# Should not raise for zero tokens, but will fail validation
with pytest.raises(ValueError, match="Schema validation failed"):
await structured(
schema=SimpleModel,
stream=whitespace_stream,
detect_zero_tokens=False,
)
class TestStructuredObject:
"""Test structured_object helper."""
@pytest.mark.asyncio
async def test_structured_object_basic(self):
"""Test basic structured_object usage."""
async def json_stream():
yield Event(type=EventType.TOKEN, text='{"name": "Alice", "age": 30}')
yield Event(type=EventType.COMPLETE)
result = await structured_object(
{"name": str, "age": int},
stream=json_stream,
)
assert result.data.name == "Alice"
assert result.data.age == 30
@pytest.mark.asyncio
async def test_structured_object_with_defaults(self):
"""Test structured_object with default values."""
async def json_stream():
yield Event(type=EventType.TOKEN, text='{"name": "Bob"}')
yield Event(type=EventType.COMPLETE)
result = await structured_object(
{"name": str, "active": (bool, True)},
stream=json_stream,
)
assert result.data.name == "Bob"
assert result.data.active is True
class TestStructuredArray:
"""Test structured_array helper."""
@pytest.mark.asyncio
async def test_structured_array_basic(self):
"""Test basic structured_array usage."""
async def json_stream():
yield Event(
type=EventType.TOKEN,
text='[{"value": "a"}, {"value": "b"}]',
)
yield Event(type=EventType.COMPLETE)
result = await structured_array(
SimpleModel,
stream=json_stream,
)
assert len(result.data) == 2
assert result.data[0].value == "a"
assert result.data[1].value == "b"
@pytest.mark.asyncio
async def test_structured_array_with_telemetry(self):
"""Test structured_array with monitoring enabled."""
async def json_stream():
yield Event(type=EventType.TOKEN, text='[{"value": "test"}]')
yield Event(type=EventType.COMPLETE)
result = await structured_array(
SimpleModel,
stream=json_stream,
monitoring=True,
)
assert result.telemetry is not None
assert result.telemetry.schema_name is not None
assert "list[SimpleModel]" in result.telemetry.schema_name
class TestStreamFactoryRetryBehavior:
"""Test that factory functions are called fresh on each retry attempt.
This tests the fix for the "stream already consumed" bug where factory
functions were not being called on each retry, causing streams to be
reused and fail with "ReadableStream is locked" or similar errors.
"""
@pytest.mark.asyncio
async def test_factory_called_fresh_on_each_retry_structured(self):
"""Test that factory is called fresh on each retry in structured()."""
factory_call_count = 0
def stream_factory():
nonlocal factory_call_count
factory_call_count += 1
async def gen():
if factory_call_count == 1:
# First attempt: invalid JSON that will fail validation
yield Event(type=EventType.TOKEN, text='{"wrong": "field"}')
else:
# Subsequent attempts: valid JSON
yield Event(type=EventType.TOKEN, text='{"value": "success"}')
yield Event(type=EventType.COMPLETE)
return gen()
result = await structured(
schema=SimpleModel,
stream=stream_factory,
retry=Retry(attempts=3),
)
assert result.data.value == "success"
assert factory_call_count == 2 # Called twice: first failed, second succeeded
@pytest.mark.asyncio
async def test_factory_called_fresh_on_each_retry_structured_array(self):
"""Test that factory is called fresh on each retry in structured_array()."""
factory_call_count = 0
def stream_factory():
nonlocal factory_call_count
factory_call_count += 1
async def gen():
if factory_call_count == 1:
# First attempt: invalid JSON that will fail validation
yield Event(type=EventType.TOKEN, text='[{"wrong": "field"}]')
else:
# Subsequent attempts: valid JSON
yield Event(type=EventType.TOKEN, text='[{"value": "success"}]')
yield Event(type=EventType.COMPLETE)
return gen()
result = await structured_array(
item_schema=SimpleModel,
stream=stream_factory,
retry=Retry(attempts=3),
)
assert len(result.data) == 1
assert result.data[0].value == "success"
assert factory_call_count == 2 # Called twice: first failed, second succeeded
@pytest.mark.asyncio
async def test_factory_exhausts_all_retries_on_persistent_failure(self):
"""Test that all retry attempts are used when validation keeps failing."""
factory_call_count = 0
def stream_factory():
nonlocal factory_call_count
factory_call_count += 1
async def gen():
# Always return invalid JSON
yield Event(type=EventType.TOKEN, text='{"wrong": "field"}')
yield Event(type=EventType.COMPLETE)
return gen()
with pytest.raises(ValueError, match="Schema validation failed"):
await structured(
schema=SimpleModel,
stream=stream_factory,
retry=Retry(attempts=3),
)
# Factory should have been called 3 times (once per retry attempt)
assert factory_call_count == 3
@pytest.mark.asyncio
async def test_factory_not_called_after_success(self):
"""Test that factory is not called again after successful validation."""
factory_call_count = 0
def stream_factory():
nonlocal factory_call_count
factory_call_count += 1
async def gen():
# Always return valid JSON
yield Event(type=EventType.TOKEN, text='{"value": "test"}')
yield Event(type=EventType.COMPLETE)
return gen()
result = await structured(
schema=SimpleModel,
stream=stream_factory,
retry=Retry(attempts=5),
)
assert result.data.value == "test"
assert factory_call_count == 1 # Only called once since first attempt succeeded
@pytest.mark.asyncio
async def test_fallback_factory_called_fresh_on_retry(self):
"""Test that fallback factory functions are also called fresh on retry."""
main_call_count = 0
fallback_call_count = 0
def main_factory():
nonlocal main_call_count
main_call_count += 1
async def gen():
# Main always fails
yield Event(type=EventType.TOKEN, text='{"wrong": "field"}')
yield Event(type=EventType.COMPLETE)
return gen()
def fallback_factory():
nonlocal fallback_call_count
fallback_call_count += 1
async def gen():
if fallback_call_count == 1:
# First fallback attempt fails
yield Event(type=EventType.TOKEN, text='{"also_wrong": "field"}')
else:
# Second fallback attempt succeeds
yield Event(type=EventType.TOKEN, text='{"value": "from_fallback"}')
yield Event(type=EventType.COMPLETE)
return gen()
result = await structured(
schema=SimpleModel,
stream=main_factory,
fallbacks=[fallback_factory],
retry=Retry(attempts=2),
)
assert result.data.value == "from_fallback"
assert main_call_count == 2 # Main tried twice
assert fallback_call_count == 2 # Fallback tried twice, second succeeded
@pytest.mark.asyncio
async def test_async_factory_called_fresh_on_retry(self):
"""Test that async factory functions are called fresh on each retry."""
factory_call_count = 0
async def async_stream_factory():
nonlocal factory_call_count
factory_call_count += 1
async def gen():
if factory_call_count == 1:
yield Event(type=EventType.TOKEN, text='{"wrong": "field"}')
else:
yield Event(type=EventType.TOKEN, text='{"value": "async_success"}')
yield Event(type=EventType.COMPLETE)
return gen()
result = await structured(
schema=SimpleModel,
stream=async_stream_factory,
retry=Retry(attempts=3),
)
assert result.data.value == "async_success"
assert factory_call_count == 2
class TestStructuredStrictMode:
"""Test strict_mode parameter for rejecting extra fields."""
@pytest.mark.asyncio
async def test_strict_mode_rejects_extra_fields(self):
"""Test that strict_mode rejects extra fields not in schema."""
async def json_stream():
# JSON with extra field "extra_field" not in SimpleModel
yield Event(
type=EventType.TOKEN,
text='{"value": "test", "extra_field": "should_fail"}',
)
yield Event(type=EventType.COMPLETE)
with pytest.raises(ValueError, match="Extra field"):
await structured(
SimpleModel,
stream=json_stream,
strict_mode=True,
)
@pytest.mark.asyncio
async def test_strict_mode_allows_valid_fields(self):
"""Test that strict_mode allows JSON with only valid fields."""
async def json_stream():
yield Event(
type=EventType.TOKEN,
text='{"value": "test"}',
)
yield Event(type=EventType.COMPLETE)
result = await structured(
SimpleModel,
stream=json_stream,
strict_mode=True,
)
assert result.data.value == "test"
@pytest.mark.asyncio
async def test_non_strict_mode_allows_extra_fields(self):
"""Test that non-strict mode (default) ignores extra fields."""
async def json_stream():
# JSON with extra field - should be ignored in non-strict mode
yield Event(
type=EventType.TOKEN,
text='{"value": "test", "extra_field": "ignored"}',
)
yield Event(type=EventType.COMPLETE)
result = await structured(
SimpleModel,
stream=json_stream,
strict_mode=False,
)
assert result.data.value == "test"