Files
notifications-admin/tests/app/models/test_base_model.py
T

88 lines
2.0 KiB
Python
Raw Normal View History

2019-07-09 11:47:40 +01:00
import pytest
from app.models import JSONModel
def test_looks_up_from_dict():
class Custom(JSONModel):
ALLOWED_PROPERTIES = {"foo"}
2019-07-09 11:47:40 +01:00
assert Custom({"foo": "bar"}).foo == "bar"
2019-07-09 11:47:40 +01:00
def test_raises_when_overriding_custom_properties():
2019-07-09 11:47:40 +01:00
class Custom(JSONModel):
ALLOWED_PROPERTIES = {"foo"}
2019-07-09 11:47:40 +01:00
@property
def foo(self):
pass
2019-07-09 11:47:40 +01:00
with pytest.raises(AttributeError) as e:
Custom({"foo": "NOPE"})
assert (
str(e.value)
== "property 'foo' of 'test_raises_when_overriding_custom_properties.<locals>.Custom' object has no setter"
)
2019-07-09 11:47:40 +01:00
@pytest.mark.parametrize(
"json_response",
2023-09-08 17:58:06 -04:00
[
{},
{"foo": "bar"}, # Should still raise an exception
2023-09-08 17:58:06 -04:00
],
)
2019-07-09 11:47:40 +01:00
def test_model_raises_for_unknown_attributes(json_response):
2020-07-03 14:07:40 +01:00
class Custom(JSONModel):
ALLOWED_PROPERTIES = set()
model = Custom(json_response)
2019-07-09 11:47:40 +01:00
assert model.ALLOWED_PROPERTIES == set()
with pytest.raises(AttributeError) as e:
model.foo
assert str(e.value) == "'Custom' object has no attribute 'foo'"
2019-07-09 11:47:40 +01:00
def test_model_raises_keyerror_if_item_missing_from_dict():
class Custom(JSONModel):
ALLOWED_PROPERTIES = {"foo"}
2019-07-09 11:47:40 +01:00
with pytest.raises(AttributeError) as e:
2019-07-09 11:47:40 +01:00
Custom({}).foo
assert str(e.value) == "'Custom' object has no attribute 'foo'"
2019-07-09 11:47:40 +01:00
@pytest.mark.parametrize(
"json_response",
2023-09-08 17:58:06 -04:00
[
{},
{"foo": "bar"}, # Should be ignored
2023-09-08 17:58:06 -04:00
],
)
2019-07-09 11:47:40 +01:00
def test_model_doesnt_swallow_attribute_errors(json_response):
class Custom(JSONModel):
2020-07-03 14:07:40 +01:00
ALLOWED_PROPERTIES = set()
2021-03-08 15:36:23 +00:00
2019-07-09 11:47:40 +01:00
@property
def foo(self):
raise AttributeError("Something has gone wrong")
2019-07-09 11:47:40 +01:00
with pytest.raises(AttributeError) as e:
Custom(json_response).foo
assert str(e.value) == "Something has gone wrong"
def test_dynamic_properties_are_introspectable():
class Custom(JSONModel):
ALLOWED_PROPERTIES = {"foo", "bar", "baz"}
model = Custom({"foo": None, "bar": None, "baz": None})
assert dir(model)[-3:] == ["bar", "baz", "foo"]