Search code examples
unit-testinghttpflaskflask-testing

WrapperTestResponse' object has no attribute 'text'


  1. Currently I'm writing a unite testing for my flask project. I wrote a function to test the login feature. When I run the unit test, it showed some error message.

FAILED unit_test.py::TestClass::test_login - AttributeError: 'WrapperTestResponse' object has no attribute 'text'

2.Here is my code for the unit testing implementation, I can get the status code successfully but not the text. Did I make some mistakes?

import unittest
from app import app
import requests
from flask import request
import json



class TestClass(unittest.TestCase):
    def setup_class(self):
        app.config['TESTING'] = True  
        self.app = app.test_client()

    def teardown_class(self):
        """Do the testing """
        pass

    def test_login(self):
        response = self.app.get('/login')
        print(response)
        data = {'username': '[email protected]', 'password': '12345678'}
        response = app.test_client().post('/login', data=json.dumps(data))
        self.assertEqual(response.status_code, 200)
        print('--------------')
        self.assertEqual(response.text, "Invalid login credentials")

Solution

  • I think you are looking for response.data instead

    A descriptor that calls get_data() and set_data().

    get_data gives

    The string representation of the response body...

    Example output if your view function returns 'Invalid login credentials':

    >>> response.data
    b'Invalid login credentials'