From 620d3ee1398d38dfebb89eb297f40ac944e8f41d Mon Sep 17 00:00:00 2001 From: Michal Klich Date: Fri, 25 May 2018 14:43:35 +0200 Subject: [PATCH] Add __str__ method to Document class It is helpful when passing object to logger utilities. --- flask_hal/document.py | 3 +++ tests/test_document.py | 48 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 51 insertions(+) diff --git a/flask_hal/document.py b/flask_hal/document.py index fbd19db..897c830 100644 --- a/flask_hal/document.py +++ b/flask_hal/document.py @@ -41,6 +41,9 @@ def __init__(self, data=None, links=None, embedded=None): self.embedded = embedded or {} self.links = links or link.Collection() + def __str__(self): + return str(self.to_dict()) + @property def links(self): return self._links diff --git a/tests/test_document.py b/tests/test_document.py index 2034d1d..d7aab5e 100644 --- a/tests/test_document.py +++ b/tests/test_document.py @@ -7,6 +7,54 @@ from flask_hal.document import Document, Embedded +def test_empty_document_str(): + app = flask.Flask(__name__) + with app.test_request_context('/entity/231'): + document = Document() + assert str(document) == str({'_links': {'self': {'href': '/entity/231'}}}) + + +def test_str_with_embedded_document(): + app = flask.Flask(__name__) + with app.test_request_context('/entity/231'): + document = Document( + embedded={ + 'orders': Embedded( + embedded={'details': Embedded( + data={'details': {}} + )}, + links=link.Collection( + link.Link('foo', 'www.foo.com'), + link.Link('boo', 'www.boo.com') + ), + data={'total': 30}, + ) + }, + data={'currentlyProcessing': 14} + ) + expected = { + '_links': { + 'self': { + 'href': flask.request.path + } + }, + '_embedded': { + 'orders': { + '_links': { + 'foo': {'href': 'www.foo.com'}, + 'boo': {'href': 'www.boo.com'} + }, + '_embedded': { + 'details': {'details': {}} + }, + 'total': 30, + } + }, + 'currentlyProcessing': 14 + } + assert str(expected) == str(document) + + def test_document_should_have_link_self(): app = flask.Flask(__name__) with app.test_request_context('/entity/231'):