Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django rest framework custom renderer in testing response

I'm trying to make my testing code in my django app. My app has a custom renderer class so the response will look like this:

{
    "code": 422,
    "message": "Unprocessable Entity",
    "data": {
        "non_field_errors": [
            "Unable to log in with provided credentials."
        ]
    }
}

My test code:

class AuthenticationTestCase(TestCase):
    """Test login and registration"""

    def setUp(self):
        self.client = APIClient()

    def test_login_success(self):
        """Test success login"""

        payload = {
            'email': '[email protected]',
            'password': 'password',
            'is_active': True
        }

        create_user(**payload)

        res = self.client.post(LOGIN_URL, payload)

        self.assertEqual(res.data['code'], status.HTTP_200_OK)

The client response only return:

"non_field_errors": [
    "Unable to log in with provided credentials."
]

Question is, can I make my testing client response using my custom renderer class as well?

EDIT:

This is my custom renderer class:

class CustomRenderer(JSONRenderer):

    def render(self, data, accepted_media_type=None, renderer_context=None):
        status_code = renderer_context['response'].status_code
        response = {
            'code': status_code,
            'message': renderer_context['response'].status_text,
            'data': data,
        }

        renderer_context['response'].status_code = 200

        return super(CustomRenderer, self) \
            .render(response, accepted_media_type, renderer_context)
like image 294
Denny Rustandi Avatar asked Dec 20 '25 08:12

Denny Rustandi


1 Answers

I found the solution. I need to set response's data in renderer class to my custom response like this:

renderer_context['response'].data = response
like image 175
Denny Rustandi Avatar answered Dec 24 '25 12:12

Denny Rustandi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!