Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add .text attribute for .get_data(as_text=True) #138

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions docs/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,26 @@ a special ``json`` attribute appended to the ``Response`` object::
response = self.client.get("/ajax/")
self.assertEquals(response.json, dict(success=True))

Testing text responses
----------------------

Without Flask-Testing, if you are testing a view that returns text responses (like HTML),
you can test the output using the ``data`` attribute or the ``get_data()`` method on the
``Response`` object. These returns byte strings, not a unicode string. To get the
textual representation, you need to use ``get_data(as_text=True)``.

With Flask-Testing, there is now a convenience attribute, ``text``, on the
``Response.object``, providing the same functionality as ``get_data(as_text=True)``::

@app.route("/html/")
def some_html():
return "<html><body><h1>Hello</h1></body></html>"

class TestViews(TestCase):
def test_some_html(self):
response = self.client.get("/html/")
self.assertIn(response.text, "<h1>Hello</h1>")

Opt to not render the templates
-------------------------------

Expand Down
12 changes: 11 additions & 1 deletion flask_testing/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,8 +76,18 @@ def json(self):
return json.loads(self.data)


class TextResponseMixin(object):
"""
Mixin with testing helper for text responses.
"""

@cached_property
def text(self):
return self.get_data(as_text=True)


def _make_test_response(response_class):
class TestResponse(response_class, JsonResponseMixin):
class TestResponse(response_class, JsonResponseMixin, TextResponseMixin):
pass

return TestResponse
Expand Down