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'}
|
|
|
|
|
|
|
|
|
|
assert Custom({'foo': 'bar'}).foo == 'bar'
|
|
|
|
|
|
|
|
|
|
|
2020-10-28 10:03:02 +00:00
|
|
|
def test_raises_when_overriding_custom_properties():
|
2019-07-09 11:47:40 +01:00
|
|
|
|
|
|
|
|
class Custom(JSONModel):
|
|
|
|
|
|
|
|
|
|
ALLOWED_PROPERTIES = {'foo'}
|
|
|
|
|
|
|
|
|
|
@property
|
|
|
|
|
def foo(self):
|
2020-10-28 10:03:02 +00:00
|
|
|
pass
|
2019-07-09 11:47:40 +01:00
|
|
|
|
2020-10-28 10:03:02 +00:00
|
|
|
with pytest.raises(AttributeError) as e:
|
|
|
|
|
Custom({'foo': 'NOPE'})
|
|
|
|
|
|
|
|
|
|
assert str(e.value) == "can't set attribute"
|
2019-07-09 11:47:40 +01:00
|
|
|
|
|
|
|
|
|
|
|
|
|
@pytest.mark.parametrize('json_response', (
|
|
|
|
|
{},
|
|
|
|
|
{'foo': 'bar'}, # Should still raise an exception
|
|
|
|
|
))
|
|
|
|
|
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
|
|
|
|
|
|
2020-10-19 15:36:50 +01:00
|
|
|
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'}
|
|
|
|
|
|
2020-10-19 15:36:50 +01:00
|
|
|
with pytest.raises(AttributeError) as e:
|
2019-07-09 11:47:40 +01:00
|
|
|
Custom({}).foo
|
|
|
|
|
|
2020-10-19 15:36:50 +01:00
|
|
|
assert str(e.value) == "'Custom' object has no attribute 'foo'"
|
2019-07-09 11:47:40 +01:00
|
|
|
|
|
|
|
|
|
|
|
|
|
@pytest.mark.parametrize('json_response', (
|
|
|
|
|
{},
|
|
|
|
|
{'foo': 'bar'}, # Should be ignored
|
|
|
|
|
))
|
|
|
|
|
def test_model_doesnt_swallow_attribute_errors(json_response):
|
|
|
|
|
|
|
|
|
|
class Custom(JSONModel):
|
2020-07-03 14:07:40 +01:00
|
|
|
ALLOWED_PROPERTIES = set()
|
2019-07-09 11:47:40 +01:00
|
|
|
@property
|
|
|
|
|
def foo(self):
|
|
|
|
|
raise AttributeError('Something has gone wrong')
|
|
|
|
|
|
|
|
|
|
with pytest.raises(AttributeError) as e:
|
|
|
|
|
Custom(json_response).foo
|
|
|
|
|
|
|
|
|
|
assert str(e.value) == 'Something has gone wrong'
|
2020-04-14 09:39:39 +01:00
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_dynamic_properties_are_introspectable():
|
|
|
|
|
|
|
|
|
|
class Custom(JSONModel):
|
|
|
|
|
ALLOWED_PROPERTIES = {'foo', 'bar', 'baz'}
|
|
|
|
|
|
2020-10-19 15:36:50 +01:00
|
|
|
model = Custom({'foo': None, 'bar': None, 'baz': None})
|
|
|
|
|
|
|
|
|
|
assert dir(model)[-3:] == ['bar', 'baz', 'foo']
|