flask-testing
flask-testing copied to clipboard
Make "json" property optionally callable
The requests library has a callable json attribute.
To make TestResponse.json "optionally callable", we use the following work-around:
class JsonResponseMixin(object):
"""
Mixin with testing helper methods
"""
@cached_property
def json(self):
"""Return response data as a Python object.
The data is deserialized using the JSON format.
"""
# Note that during testing, this response class may already
# provide a JSON property. We re-implement it here for
# consistency.
value = loads(self.data)
# Adapt value to make it callable. Alas, the 'requests'
# library changed its response class such that the JSON
# property is callable.
cls = type(value)
return type(cls.__name__, (cls, ), {
'__call__': lambda v: cls(v),
'__module__': cls.__module__,
'__reduce__': lambda v: (cls, (cls(v), )),
})(value)
That is, you can call it or use it directly – because it's a dict whose callable returns the dict.
I can understand you wish to have the same API like requests but with this workaround there can be too much pitfalls.
Maybe we can talk about a general change to a function instead a property.
It actually works really well (flawlessly) in practice. We use it in our system.
Note that in any case, this is a testing framework. It is not a library that's used in production.
-Malthe
On Wednesday, July 23, 2014, Christoph Heer [email protected] wrote:
I can understand you wish to have the same API like requests but with this workaround there can be too much pitfalls. Maybe we can talk about a general change to a function instead a property.
— Reply to this email directly or view it on GitHub https://github.com/jarus/flask-testing/issues/58#issuecomment-49888082.
It actually works really well (flawlessly) in practice. We use it in our system.
Okay, cool.
Note that in any case, this is a testing framework. It is not a library that's used in production.
Yes, sure but a testing framework/extension shouldn't break tests of users.
The testing framework should reflect the actual usage. If it does not, then it's broken. But if it does, then it's okay.
But I think perhaps it should be a switch that you can enable on the test class such as json_property = True.