Django test print or log failure

1.7k views Asked by At

I have a django_rest_framework test (the problem is the same with a regular django test) that looks like this:

from rest_framework.test import APITestCase

class APITests(APITestCase):

    # tests for unauthorized access
    def test_unauthorized(self):
        ...
        for api in apipoints:
            response = self.client.options(api)
            self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)

I have a url that fails, the terminal shows this:

FAIL: test_unauthorized (app.misuper.tests.APITests) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/alejandro/...",

line 64, in test_unauthorized

self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) AssertionError: 200 != 403

Ok, how can I know which url failed the test? I am iterating through all urls that require login, that is many urls, how can I print the one that failed the test?

1

There are 1 answers

0
wim On BEST ANSWER

For a simple quick-fix, you can pass the apipoint in the third parameter of the assertion method:

>>> from unittest import TestCase
>>> TestCase('__init__').assertEqual(1, 2, msg='teh thing is b0rked')
AssertionError: teh thing is b0rked

In the spirit of unit testing, these should really be each different test methods rather than only one test method with the loop. Check out nose_parameterized for help with making that more DRY. You'll decorate the test method like this:

from nose_parameterized import parameterized

@parameterized.expand(apipoints)
def test_unauthorized(self, apipoint):
    response = self.client.options(apipoint)
    self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)

The decorator will generate different test methods for each endpoint, so that they can pass/fail independently of one another.

Although this package has nose in the name, it's also compatible with other runners such as unittest and py.test.