diff --git a/docs/index.rst b/docs/index.rst index b0b288c..5db1f23 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -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 "

Hello

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

Hello

") + Opt to not render the templates ------------------------------- diff --git a/flask_testing/utils.py b/flask_testing/utils.py index 7362c40..d7e044e 100644 --- a/flask_testing/utils.py +++ b/flask_testing/utils.py @@ -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