File: test_functions.py

package info (click to toggle)
pydantic-core 2.41.5-1
  • links: PTS, VCS
  • area: main
  • in suites: forky
  • size: 3,836 kB
  • sloc: python: 35,821; javascript: 211; makefile: 128
file content (707 lines) | stat: -rw-r--r-- 25,249 bytes parent folder | download | duplicates (2)
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
import json
import platform
import re
import sys
from collections import deque
from operator import attrgetter
from pathlib import Path

import pytest

from pydantic_core import (
    PydanticOmit,
    PydanticSerializationError,
    PydanticSerializationUnexpectedValue,
    SchemaSerializer,
    core_schema,
)


def repr_function(value, _info):
    return repr(value)


@pytest.mark.parametrize(
    'value,expected_python,expected_json',
    [(None, 'None', b'"None"'), (1, '1', b'"1"'), ([1, 2, 3], '[1, 2, 3]', b'"[1, 2, 3]"')],
)
def test_function_general(value, expected_python, expected_json):
    s = SchemaSerializer(
        core_schema.any_schema(
            serialization=core_schema.plain_serializer_function_ser_schema(repr_function, info_arg=True)
        )
    )
    assert s.to_python(value) == expected_python
    assert s.to_json(value) == expected_json
    assert s.to_python(value, mode='json') == json.loads(expected_json)


def repr_function_no_info(value):
    return repr(value)


@pytest.mark.parametrize(
    'value,expected_python,expected_json',
    [(None, 'None', b'"None"'), (1, '1', b'"1"'), ([1, 2, 3], '[1, 2, 3]', b'"[1, 2, 3]"')],
)
def test_function_no_info(value, expected_python, expected_json):
    s = SchemaSerializer(
        core_schema.any_schema(serialization=core_schema.plain_serializer_function_ser_schema(repr_function_no_info))
    )
    assert s.to_python(value) == expected_python
    assert s.to_json(value) == expected_json
    assert s.to_python(value, mode='json') == json.loads(expected_json)


def test_function_args():
    f_info = None

    def double(value, info):
        nonlocal f_info
        f_info = vars(info)
        return value * 2

    s = SchemaSerializer(
        core_schema.any_schema(serialization=core_schema.plain_serializer_function_ser_schema(double, info_arg=True))
    )
    assert s.to_python(4) == 8
    # insert_assert(f_info)
    assert f_info == {
        'mode': 'python',
        'by_alias': None,
        'exclude_unset': False,
        'exclude_defaults': False,
        'exclude_none': False,
        'exclude_computed_fields': False,
        'round_trip': False,
        'serialize_as_any': False,
    }
    assert s.to_python('x') == 'xx'

    assert s.to_python(4, mode='foobar', by_alias=True) == 8
    # insert_assert(f_info)
    assert f_info == {
        'mode': 'foobar',
        'by_alias': True,
        'exclude_unset': False,
        'exclude_defaults': False,
        'exclude_none': False,
        'exclude_computed_fields': False,
        'round_trip': False,
        'serialize_as_any': False,
    }

    assert s.to_json(42) == b'84'
    # insert_assert(f_info)
    assert f_info == {
        'mode': 'json',
        'by_alias': None,
        'exclude_unset': False,
        'exclude_defaults': False,
        'exclude_none': False,
        'exclude_computed_fields': False,
        'round_trip': False,
        'serialize_as_any': False,
    }

    assert s.to_python(7, mode='json', by_alias=False, exclude_unset=True) == 14
    # insert_assert(f_info)
    assert f_info == {
        'mode': 'json',
        'by_alias': False,
        'exclude_unset': True,
        'exclude_defaults': False,
        'exclude_none': False,
        'exclude_computed_fields': False,
        'round_trip': False,
        'serialize_as_any': False,
    }

    assert s.to_python(1, include={1, 2, 3}, exclude={'foo': {'bar'}}) == 2
    # insert_assert(f_info)
    assert f_info == {
        'include': {3, 2, 1},
        'exclude': {'foo': {'bar'}},
        'mode': 'python',
        'by_alias': None,
        'exclude_unset': False,
        'exclude_defaults': False,
        'exclude_none': False,
        'exclude_computed_fields': False,
        'round_trip': False,
        'serialize_as_any': False,
    }

    assert s.to_python(1, context='context') == 2
    # insert_assert(f_info)
    assert f_info == {
        'context': 'context',
        'mode': 'python',
        'by_alias': None,
        'exclude_unset': False,
        'exclude_defaults': False,
        'exclude_none': False,
        'exclude_computed_fields': False,
        'round_trip': False,
        'serialize_as_any': False,
    }


def test_function_error():
    def raise_error(value, _info):
        raise TypeError('foo')

    s = SchemaSerializer(
        core_schema.any_schema(
            serialization=core_schema.plain_serializer_function_ser_schema(raise_error, info_arg=True)
        )
    )

    msg = 'Error calling function `raise_error`: TypeError: foo$'
    with pytest.raises(PydanticSerializationError, match=msg) as exc_info:
        s.to_python('abc')
    assert isinstance(exc_info.value.__cause__, TypeError)

    with pytest.raises(PydanticSerializationError, match=msg) as exc_info:
        s.to_python('abc', mode='json')
    assert isinstance(exc_info.value.__cause__, TypeError)

    with pytest.raises(PydanticSerializationError, match=msg):
        s.to_json('foo')


def test_function_error_keys():
    def raise_error(value, _info):
        raise TypeError('foo')

    s = SchemaSerializer(
        core_schema.dict_schema(
            core_schema.any_schema(
                serialization=core_schema.plain_serializer_function_ser_schema(raise_error, info_arg=True)
            ),
            core_schema.int_schema(),
        )
    )

    msg = 'Error calling function `raise_error`: TypeError: foo$'
    with pytest.raises(PydanticSerializationError, match=msg) as exc_info:
        s.to_python({'abc': 1})
    assert isinstance(exc_info.value.__cause__, TypeError)

    with pytest.raises(PydanticSerializationError, match=msg) as exc_info:
        s.to_python({'abc': 1}, mode='json')
    assert isinstance(exc_info.value.__cause__, TypeError)

    with pytest.raises(PydanticSerializationError, match=msg):
        s.to_json({'abc': 1})


def test_function_known_type():
    def append_42(value, _info):
        if isinstance(value, list):
            value.append(42)
        return value

    s = SchemaSerializer(
        core_schema.any_schema(
            serialization=core_schema.plain_serializer_function_ser_schema(
                append_42, info_arg=True, return_schema=core_schema.list_schema(core_schema.int_schema())
            )
        )
    )
    assert s.to_python([1, 2, 3]) == [1, 2, 3, 42]
    assert s.to_python([1, 2, 3], mode='json') == [1, 2, 3, 42]
    assert s.to_json([1, 2, 3]) == b'[1,2,3,42]'

    msg = r"Expected `list\[int\]` - serialized value may not be as expected \[input_value='abc', input_type=str\]"
    with pytest.warns(UserWarning, match=msg):
        assert s.to_python('abc') == 'abc'

    with pytest.warns(UserWarning, match=msg):
        assert s.to_python('abc', mode='json') == 'abc'

    with pytest.warns(UserWarning, match=msg):
        assert s.to_json('abc') == b'"abc"'


def test_function_args_str():
    def append_args(value, info):
        return f'{value} info={info}'

    s = SchemaSerializer(
        core_schema.any_schema(
            serialization=core_schema.plain_serializer_function_ser_schema(
                append_args, info_arg=True, return_schema=core_schema.str_schema()
            )
        )
    )
    assert s.to_python(123) == (
        "123 info=SerializationInfo(include=None, exclude=None, context=None, mode='python', by_alias=False, exclude_unset=False, "
        'exclude_defaults=False, exclude_none=False, exclude_computed_fields=False, round_trip=False, serialize_as_any=False)'
    )
    assert s.to_python(123, mode='other') == (
        "123 info=SerializationInfo(include=None, exclude=None, context=None, mode='other', by_alias=False, exclude_unset=False, "
        'exclude_defaults=False, exclude_none=False, exclude_computed_fields=False, round_trip=False, serialize_as_any=False)'
    )
    assert s.to_python(123, include={'x'}) == (
        "123 info=SerializationInfo(include={'x'}, exclude=None, context=None, mode='python', by_alias=False, exclude_unset=False, "
        'exclude_defaults=False, exclude_none=False, exclude_computed_fields=False, round_trip=False, serialize_as_any=False)'
    )
    assert s.to_python(123, context='context') == (
        "123 info=SerializationInfo(include=None, exclude=None, context='context', mode='python', by_alias=False, exclude_unset=False, "
        'exclude_defaults=False, exclude_none=False, exclude_computed_fields=False, round_trip=False, serialize_as_any=False)'
    )
    assert s.to_python(123, mode='json', exclude={1: {2}}) == (
        "123 info=SerializationInfo(include=None, exclude={1: {2}}, context=None, mode='json', by_alias=False, exclude_unset=False, "
        'exclude_defaults=False, exclude_none=False, exclude_computed_fields=False, round_trip=False, serialize_as_any=False)'
    )
    assert s.to_json(123) == (
        b"\"123 info=SerializationInfo(include=None, exclude=None, context=None, mode='json', by_alias=False, exclude_unset=False, "
        b'exclude_defaults=False, exclude_none=False, exclude_computed_fields=False, round_trip=False, serialize_as_any=False)"'
    )


def test_dict_keys():
    def fmt(value, _info):
        return f'<{value}>'

    s = SchemaSerializer(
        core_schema.dict_schema(
            core_schema.int_schema(serialization=core_schema.plain_serializer_function_ser_schema(fmt, info_arg=True))
        )
    )
    assert s.to_python({1: True}) == {'<1>': True}


def test_function_as_key():
    s = SchemaSerializer(
        core_schema.dict_schema(
            core_schema.any_schema(
                serialization=core_schema.plain_serializer_function_ser_schema(repr_function, info_arg=True)
            ),
            core_schema.any_schema(),
        )
    )
    assert s.to_python({123: 4}) == {'123': 4}
    assert s.to_python({123: 4}, mode='json') == {'123': 4}
    assert s.to_json({123: 4}) == b'{"123":4}'


def test_function_only_json():
    def double(value, _):
        return value * 2

    s = SchemaSerializer(
        core_schema.any_schema(
            serialization=core_schema.plain_serializer_function_ser_schema(double, info_arg=True, when_used='json')
        )
    )
    assert s.to_python(4) == 4
    assert s.to_python(4, mode='foobar') == 4

    assert s.to_python(4, mode='json') == 8
    assert s.to_json(4) == b'8'


def test_function_unless_none():
    s = SchemaSerializer(
        core_schema.any_schema(
            serialization=core_schema.plain_serializer_function_ser_schema(
                repr_function, info_arg=True, when_used='unless-none'
            )
        )
    )
    assert s.to_python(4) == '4'
    assert s.to_python(None) is None

    assert s.to_python(4, mode='json') == '4'
    assert s.to_python(None, mode='json') is None
    assert s.to_json(4) == b'"4"'
    assert s.to_json(None) == b'null'


def test_wrong_return_type():
    s = SchemaSerializer(
        core_schema.any_schema(
            serialization=core_schema.plain_serializer_function_ser_schema(
                repr_function, info_arg=True, return_schema=core_schema.int_schema()
            )
        )
    )
    with pytest.warns(
        UserWarning,
        match=r"Expected `int` - serialized value may not be as expected \[input_value='123', input_type=str\]",
    ):
        assert s.to_python(123) == '123'
    with pytest.warns(
        UserWarning,
        match=r"Expected `int` - serialized value may not be as expected \[input_value='123', input_type=str\]",
    ):
        assert s.to_python(123, mode='json') == '123'
    with pytest.warns(
        UserWarning,
        match=r"Expected `int` - serialized value may not be as expected \[input_value='123', input_type=str\]",
    ):
        assert s.to_json(123) == b'"123"'


def test_function_wrap():
    def f(value, serializer, _info):
        return f'result={serializer(len(value))} repr={serializer!r}'

    s = SchemaSerializer(
        core_schema.int_schema(serialization=core_schema.wrap_serializer_function_ser_schema(f, info_arg=True))
    )
    assert s.to_python('foo') == 'result=3 repr=SerializationCallable(serializer=int)'
    assert s.to_python('foo', mode='json') == 'result=3 repr=SerializationCallable(serializer=int)'
    assert s.to_json('foo') == b'"result=3 repr=SerializationCallable(serializer=int)"'


def test_function_wrap_return_scheam():
    def f(value, serializer):
        if value == 42:
            return 42
        return f'result={serializer(value)}'

    s = SchemaSerializer(
        core_schema.int_schema(
            serialization=core_schema.wrap_serializer_function_ser_schema(f, return_schema=core_schema.str_schema())
        )
    )
    assert s.to_python(3) == 'result=3'
    assert s.to_python(3, mode='json') == 'result=3'
    assert s.to_json(3) == b'"result=3"'
    with pytest.warns(
        UserWarning,
        match=r'Expected `str` - serialized value may not be as expected \[input_value=42, input_type=int\]',
    ):
        assert s.to_python(42) == 42
    with pytest.warns(
        UserWarning,
        match=r'Expected `str` - serialized value may not be as expected \[input_value=42, input_type=int\]',
    ):
        assert s.to_python(42, mode='json') == 42
    with pytest.warns(
        UserWarning,
        match=r'Expected `str` - serialized value may not be as expected \[input_value=42, input_type=int\]',
    ):
        assert s.to_json(42) == b'42'


def test_function_wrap_no_info():
    def f(value, serializer):
        return f'result={serializer(len(value))} repr={serializer!r}'

    s = SchemaSerializer(core_schema.int_schema(serialization=core_schema.wrap_serializer_function_ser_schema(f)))
    assert s.to_python('foo') == 'result=3 repr=SerializationCallable(serializer=int)'
    assert s.to_python('foo', mode='json') == 'result=3 repr=SerializationCallable(serializer=int)'
    assert s.to_json('foo') == b'"result=3 repr=SerializationCallable(serializer=int)"'


def test_function_wrap_custom_schema():
    def f(value, serializer, _info):
        return f'result={serializer(len(value))} repr={serializer!r}'

    s = SchemaSerializer(
        core_schema.any_schema(
            serialization=core_schema.wrap_serializer_function_ser_schema(
                f, info_arg=True, schema=core_schema.int_schema()
            )
        )
    )
    assert s.to_python('foo') == 'result=3 repr=SerializationCallable(serializer=int)'
    assert s.to_python('foo', mode='json') == 'result=3 repr=SerializationCallable(serializer=int)'
    assert s.to_json('foo') == b'"result=3 repr=SerializationCallable(serializer=int)"'


class Foobar:
    def __str__(self):
        return 'foobar!'


def test_function_wrap_fallback():
    def f(value, serializer, _info):
        return f'result={serializer(value)}'

    def fallback(v):
        return f'fallback:{v}'

    s = SchemaSerializer(
        core_schema.any_schema(
            serialization=core_schema.wrap_serializer_function_ser_schema(
                f, info_arg=True, schema=core_schema.any_schema()
            )
        )
    )
    assert s.to_python('foo') == 'result=foo'
    assert s.to_python('foo', mode='json') == 'result=foo'
    assert s.to_json('foo') == b'"result=foo"'

    assert s.to_python(Foobar()) == 'result=foobar!'
    with pytest.raises(PydanticSerializationError, match='Unable to serialize unknown type:'):
        s.to_python(Foobar(), mode='json')
    with pytest.raises(PydanticSerializationError, match='Unable to serialize unknown type:'):
        s.to_json(Foobar())

    assert s.to_python(Foobar(), fallback=fallback) == 'result=fallback:foobar!'
    assert s.to_python(Foobar(), mode='json', fallback=fallback) == 'result=fallback:foobar!'
    assert s.to_json(Foobar(), fallback=fallback) == b'"result=fallback:foobar!"'


def test_deque():
    def serialize_deque(value, serializer, info: core_schema.SerializationInfo):
        items = []
        for index, item in enumerate(value):
            try:
                v = serializer(item, index)
            except PydanticOmit:
                pass
            else:
                items.append(v)
        if info.mode_is_json():
            return items
        else:
            return deque(items)

    s = SchemaSerializer(
        core_schema.any_schema(
            serialization=core_schema.wrap_serializer_function_ser_schema(
                serialize_deque, info_arg=True, schema=core_schema.any_schema()
            )
        )
    )
    assert s.to_python(deque([1, 2, 3])) == deque([1, 2, 3])
    assert s.to_python(deque([1, 2, 3]), exclude={2}) == deque([1, 2])
    assert s.to_python(deque([1, 2, 3]), include={0}) == deque([1])
    assert s.to_python(deque([1, 2, 3]), mode='json') == [1, 2, 3]
    assert s.to_python(deque([1, 2, 3]), mode='json', exclude={2}) == [1, 2]
    assert s.to_json(deque([1, 2, 3])) == b'[1,2,3]'
    assert s.to_json(deque([1, 2, 3]), exclude={2}) == b'[1,2]'


def test_custom_mapping():
    def serialize_custom_mapping(value, serializer, _info):
        items = {}
        for k, v in value.items():
            try:
                v = serializer(v, k)
            except PydanticOmit:
                pass
            else:
                items[k] = v
        return ' '.join(f'{k}={v}' for k, v in items.items())

    s = SchemaSerializer(
        core_schema.any_schema(
            serialization=core_schema.wrap_serializer_function_ser_schema(
                serialize_custom_mapping, info_arg=True, schema=core_schema.int_schema()
            )
        )
    )
    assert s.to_python({'a': 1, 'b': 2}) == 'a=1 b=2'
    assert s.to_python({'a': 1, 'b': 2}, exclude={'b'}) == 'a=1'
    assert s.to_python({'a': 1, 'b': 2}, mode='json') == 'a=1 b=2'
    assert s.to_python({'a': 1, 'b': 2}, mode='json', include={'a'}) == 'a=1'
    assert s.to_json({'a': 1, 'b': 2}) == b'"a=1 b=2"'
    assert s.to_json({'a': 1, 'b': 2}, exclude={'b'}) == b'"a=1"'


def test_function_wrap_model():
    calls = 0

    def wrap_function(value, handler, _info):
        nonlocal calls
        calls += 1
        return handler(value)

    class MyModel:
        def __init__(self, **kwargs):
            self.__dict__.update(kwargs)

    s = SchemaSerializer(
        core_schema.model_schema(
            MyModel,
            core_schema.typed_dict_schema(
                {
                    'a': core_schema.typed_dict_field(
                        core_schema.any_schema(), serialization_exclude_if=lambda x: isinstance(x, int) and x >= 2
                    ),
                    'b': core_schema.typed_dict_field(core_schema.any_schema()),
                    'c': core_schema.typed_dict_field(core_schema.any_schema(), serialization_exclude=True),
                }
            ),
            serialization=core_schema.wrap_serializer_function_ser_schema(wrap_function, info_arg=True),
        )
    )
    m = MyModel(a=1, b=b'foobar', c='excluded')
    assert calls == 0
    assert s.to_python(m) == {'a': 1, 'b': b'foobar'}
    assert calls == 1
    assert s.to_python(m, mode='json') == {'a': 1, 'b': 'foobar'}
    assert calls == 2
    assert s.to_json(m) == b'{"a":1,"b":"foobar"}'
    assert calls == 3

    assert s.to_python(m, exclude={'b'}) == {'a': 1}
    assert calls == 4
    assert s.to_python(m, mode='json', exclude={'b'}) == {'a': 1}
    assert calls == 5
    assert s.to_json(m, exclude={'b'}) == b'{"a":1}'
    assert calls == 6

    m = MyModel(a=2, b=b'foobar', c='excluded')
    assert s.to_python(m) == {'b': b'foobar'}
    assert calls == 7
    assert s.to_python(m, mode='json') == {'b': 'foobar'}
    assert calls == 8
    assert s.to_json(m) == b'{"b":"foobar"}'
    assert calls == 9


def test_function_plain_model():
    calls = 0

    def wrap_function(value, _info):
        nonlocal calls
        calls += 1
        return value.__dict__

    class MyModel:
        def __init__(self, **kwargs):
            self.__dict__.update(kwargs)

    s = SchemaSerializer(
        core_schema.model_schema(
            MyModel,
            core_schema.typed_dict_schema(
                {
                    'a': core_schema.typed_dict_field(
                        core_schema.any_schema(), serialization_exclude_if=lambda x: x == 100
                    ),
                    'b': core_schema.typed_dict_field(core_schema.any_schema()),
                    'c': core_schema.typed_dict_field(core_schema.any_schema(), serialization_exclude=True),
                }
            ),
            serialization=core_schema.plain_serializer_function_ser_schema(wrap_function, info_arg=True),
        )
    )
    m = MyModel(a=1, b=b'foobar', c='not excluded')
    assert calls == 0
    assert s.to_python(m) == {'a': 1, 'b': b'foobar', 'c': 'not excluded'}
    assert calls == 1
    assert s.to_python(m, mode='json') == {'a': 1, 'b': 'foobar', 'c': 'not excluded'}
    assert calls == 2
    assert s.to_json(m) == b'{"a":1,"b":"foobar","c":"not excluded"}'
    assert calls == 3

    assert s.to_python(m, exclude={'b'}) == {'a': 1, 'b': b'foobar', 'c': 'not excluded'}
    assert calls == 4
    assert s.to_python(m, mode='json', exclude={'b'}) == {'a': 1, 'b': 'foobar', 'c': 'not excluded'}
    assert calls == 5
    assert s.to_json(m, exclude={'b'}) == b'{"a":1,"b":"foobar","c":"not excluded"}'
    assert calls == 6


@pytest.mark.skipif(sys.platform == 'win32', reason='Path output different on windows')
def test_wrap_return_type():
    def to_path(value, handler, _info):
        return Path(handler(value)).with_suffix('.new')

    s = SchemaSerializer(
        core_schema.str_schema(
            serialization=core_schema.wrap_serializer_function_ser_schema(
                to_path, info_arg=True, return_schema=core_schema.any_schema()
            )
        )
    )
    assert s.to_python('foobar') == Path('foobar.new')
    assert s.to_python('foobar', mode='json') == 'foobar.new'
    assert s.to_json('foobar') == b'"foobar.new"'


def test_raise_unexpected():
    def raise_unexpected(_value):
        raise PydanticSerializationUnexpectedValue('unexpected')

    s = SchemaSerializer(
        core_schema.any_schema(serialization=core_schema.plain_serializer_function_ser_schema(raise_unexpected))
    )
    with pytest.warns(UserWarning, match=r'PydanticSerializationUnexpectedValue\(unexpected\)'):
        assert s.to_python('foo') == 'foo'

    with pytest.warns(UserWarning, match=r'PydanticSerializationUnexpectedValue\(unexpected\)'):
        assert s.to_json('foo') == b'"foo"'


def test_pydantic_serialization_unexpected_value():
    v = PydanticSerializationUnexpectedValue('abc')
    assert str(v) == 'abc'
    assert repr(v) == 'PydanticSerializationUnexpectedValue(abc)'
    v = PydanticSerializationUnexpectedValue()
    assert str(v) == 'Unexpected Value'
    assert repr(v) == 'PydanticSerializationUnexpectedValue(Unexpected Value)'


def test_function_after_preserves_wrapped_serialization():
    def f(value, _info):
        return value

    s = SchemaSerializer(core_schema.with_info_after_validator_function(f, core_schema.int_schema()))
    with pytest.warns(
        UserWarning,
        match=r"Expected `int` - serialized value may not be as expected \[input_value='abc', input_type=str\]",
    ):
        assert s.to_python('abc') == 'abc'


def test_function_wrap_preserves_wrapped_serialization():
    def f(value, handler, _info):
        return handler(value)

    s = SchemaSerializer(core_schema.with_info_wrap_validator_function(f, core_schema.int_schema()))
    with pytest.warns(
        UserWarning,
        match=r"Expected `int` - serialized value may not be as expected \[input_value='abc', input_type=str\]",
    ):
        assert s.to_python('abc') == 'abc'


@pytest.mark.skipif(
    platform.python_implementation() in ('PyPy', 'GraalVM') or sys.platform in {'emscripten', 'win32'},
    reason='fails on pypy, graalpy, emscripten and windows',
)
def test_recursive_call():
    def bad_recursive(value):
        return s.to_python(value)

    s = SchemaSerializer(
        core_schema.any_schema(serialization=core_schema.plain_serializer_function_ser_schema(bad_recursive))
    )
    with pytest.raises(PydanticSerializationError) as exc_info:
        s.to_python(42)
    # insert_assert(str(exc_info.value))
    assert str(exc_info.value) == 'Error calling function `bad_recursive`: RecursionError'

    with pytest.raises(PydanticSerializationError) as exc_info:
        s.to_python(42, mode='json')
    # insert_assert(str(exc_info.value))
    assert str(exc_info.value) == 'Error calling function `bad_recursive`: RecursionError'

    with pytest.raises(PydanticSerializationError) as exc_info:
        s.to_json(42)
    # insert_assert(str(exc_info.value))
    assert str(exc_info.value) == (
        'Error serializing to JSON: PydanticSerializationError: Error calling function `bad_recursive`: RecursionError'
    )


def test_serialize_pattern():
    ser = core_schema.plain_serializer_function_ser_schema(
        attrgetter('pattern'), when_used='json', return_schema=core_schema.str_schema()
    )
    s = SchemaSerializer(core_schema.any_schema(serialization=ser))

    pattern = re.compile('^regex$')
    assert s.to_python(pattern) == pattern
    assert s.to_python(pattern, mode='json') == '^regex$'
    assert s.to_json(pattern) == b'"^regex$"'