MCPcopy
hub / github.com/pydantic/pydantic / test_composition

Function test_composition

tests/test_pipeline.py:409–468  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

407
408
409def test_composition() -> None:
410 ta = TypeAdapter[int](Annotated[int, validate_as(int).gt(10) | validate_as(int).lt(5)])
411 assert ta.validate_python(1) == 1
412 assert ta.validate_python(20) == 20
413 with pytest.raises(ValidationError):
414 ta.validate_python(9)
415
416 ta = TypeAdapter[int](Annotated[int, validate_as(int).gt(10) & validate_as(int).le(20)])
417 assert ta.validate_python(15) == 15
418 with pytest.raises(ValidationError):
419 ta.validate_python(9)
420 with pytest.raises(ValidationError):
421 ta.validate_python(21)
422
423 # test that sticking a transform in the middle doesn't break the composition
424 calls: list[tuple[str, int]] = []
425
426 def tf(step: str) -> Callable[[int], int]:
427 def inner(x: int) -> int:
428 calls.append((step, x))
429 return x
430
431 return inner
432
433 ta = TypeAdapter[int](
434 Annotated[
435 int,
436 validate_as(int).transform(tf('1')).gt(10).transform(tf('2'))
437 | validate_as(int).transform(tf('3')).lt(5).transform(tf('4')),
438 ]
439 )
440 assert ta.validate_python(1) == 1
441 assert calls == [('1', 1), ('3', 1), ('4', 1)]
442 calls.clear()
443 assert ta.validate_python(20) == 20
444 assert calls == [('1', 20), ('2', 20)]
445 calls.clear()
446 with pytest.raises(ValidationError):
447 ta.validate_python(9)
448 assert calls == [('1', 9), ('3', 9)]
449 calls.clear()
450
451 ta = TypeAdapter[int](
452 Annotated[
453 int,
454 validate_as(int).transform(tf('1')).gt(10).transform(tf('2'))
455 & validate_as(int).transform(tf('3')).le(20).transform(tf('4')),
456 ]
457 )
458 assert ta.validate_python(15) == 15
459 assert calls == [('1', 15), ('2', 15), ('3', 15), ('4', 15)]
460 calls.clear()
461 with pytest.raises(ValidationError):
462 ta.validate_python(9)
463 assert calls == [('1', 9)]
464 calls.clear()
465 with pytest.raises(ValidationError):
466 ta.validate_python(21)

Callers

nothing calls this directly

Calls 7

tfFunction · 0.85
gtMethod · 0.80
ltMethod · 0.80
leMethod · 0.80
clearMethod · 0.80
validate_pythonMethod · 0.45
transformMethod · 0.45

Tested by

no test coverage detected