def test_multiple_validators(self): """ If a list is passed as a validator, all of its items are treated as one and must pass. """ def v1(_, __, value): if value == 23: raise TypeError("omg") def v2(_, __, value): if value == 42: raise ValueError("omg") C = make_class("C", {"x": attr.ib(validator=[v1, v2])}) validate(C(1)) with pytest.raises(TypeError) as e: C(23) assert "omg" == e.value.args[0] with pytest.raises(ValueError) as e: C(42) assert "omg" == e.value.args[0]
def test_success(self): """ If the validator suceeds, nothing gets raised. """ C = make_class("C", {"x": attr(validator=lambda *a: None), "y": attr()}) validate(C(1, 2))
def test_propagates(self): """ The exception of the validator is handed through. """ def raiser(_, __, value): if value == 42: raise FloatingPointError C = make_class("C", {"x": attr.ib(validator=raiser)}) i = C(1) i.x = 42 with pytest.raises(FloatingPointError): validate(i)
def test_run_validators(self): """ Setting `_run_validators` to False prevents validators from running. """ _config._run_validators = False obj = object() def raiser(_, __, ___): raise Exception(obj) C = make_class("C", {"x": attr.ib(validator=raiser)}) c = C(1) validate(c) assert 1 == c.x _config._run_validators = True with pytest.raises(Exception): validate(c) with pytest.raises(Exception) as e: C(1) assert (obj,) == e.value.args