89 lines
1.9 KiB
Python
89 lines
1.9 KiB
Python
from dataclasses import dataclass
|
|
|
|
import pytest
|
|
|
|
from megasniff import SchemaDeflatorGenerator
|
|
from megasniff.exceptions import FieldValidationException
|
|
|
|
|
|
def test_global_strict_mode_basic():
|
|
class A:
|
|
a: int
|
|
|
|
def __init__(self, a):
|
|
self.a = a
|
|
|
|
defl = SchemaDeflatorGenerator(strict_mode=True)
|
|
fn = defl.schema_to_deflator(A)
|
|
a = fn(A(42))
|
|
|
|
assert a['a'] == 42
|
|
|
|
with pytest.raises(FieldValidationException):
|
|
fn(A(42.0))
|
|
with pytest.raises(FieldValidationException):
|
|
fn(A('42'))
|
|
with pytest.raises(FieldValidationException):
|
|
fn(A(['42']))
|
|
|
|
|
|
def test_global_strict_mode_basic_override():
|
|
class A:
|
|
a: int
|
|
|
|
def __init__(self, a):
|
|
self.a = a
|
|
|
|
defl = SchemaDeflatorGenerator(strict_mode=False)
|
|
fn = defl.schema_to_deflator(A, strict_mode_override=True)
|
|
a = fn(A(42))
|
|
|
|
assert a['a'] == 42
|
|
|
|
with pytest.raises(FieldValidationException):
|
|
fn(A(42.0))
|
|
with pytest.raises(FieldValidationException):
|
|
fn(A('42'))
|
|
with pytest.raises(FieldValidationException):
|
|
fn(A(['42']))
|
|
|
|
|
|
def test_global_strict_mode_list():
|
|
@dataclass
|
|
class A:
|
|
a: list[int]
|
|
|
|
defl = SchemaDeflatorGenerator(strict_mode=True)
|
|
fn = defl.schema_to_deflator(A)
|
|
a = fn(A([42]))
|
|
|
|
assert a['a'] == [42]
|
|
|
|
with pytest.raises(FieldValidationException):
|
|
fn(A([42.0, 42]))
|
|
|
|
|
|
def test_global_strict_mode_circular():
|
|
@dataclass
|
|
class A:
|
|
a: list[int]
|
|
|
|
@dataclass
|
|
class B:
|
|
b: list[A | int]
|
|
|
|
defl = SchemaDeflatorGenerator(strict_mode=True)
|
|
fn = defl.schema_to_deflator(B)
|
|
b = fn(B([A([]), 42]))
|
|
|
|
assert len(b['b']) == 2
|
|
assert isinstance(b['b'][0], dict)
|
|
assert len(b['b'][0]['a']) == 0
|
|
assert isinstance(b['b'][1], int)
|
|
|
|
with pytest.raises(FieldValidationException):
|
|
fn(B([42.0]))
|
|
|
|
with pytest.raises(FieldValidationException):
|
|
fn(B([A([1.1])]))
|