python
python

Reputation: 4521

How to get status code using requests library while tesing in Django

I am writing test cases for my Django application but I am using requests package in Python to access the status code, and then use the assert statement. This test case is for Staff Users only:

class StaffClientServerTestCase(TestCase):

    def test_login_staff(self):
        User.objects.create_superuser('abc', '[email protected]', '1234')
        self.client.login(username='abc', password='1234')
        self.client.get('/dashboard/')
        s = requests.get('http://localhost:8000/dashboard/')
        print s.status_code
        self.assertEqual(200, s.status_code)

Only staff users have access to the dashboard, so I created a staff user object. The following line

self.client.login(username='abc', password='1234') is coming to be true. self.client.get('/dashboard/') if I print out this line, it shows the html content of the page which means that my staff user can access the dashboard.

But when I use the request module to see the status code of dashboard url it shows that status code = 500, and my test is failing.

s = requests.get('http://localhost:8000/dashboard/') print s.status_code

Could anyone tell me where I am going wrong here? Why my status code is coming out be 500, even though the staff user can access the dashboard and print out its contents using print self.client.get('/dashboard/'). Help!

Upvotes: 1

Views: 1637

Answers (1)

doniyor
doniyor

Reputation: 37894

you can test the case in other way:

protect your views with decorator:

@user_passes_test(lambda u: u.is_staff)
def dashboard(request, ...):
    # ...

and then request with requests to see if you are banned to see the page. if you are banned (403 forbidden), then your views is working correctly. To verify if your views works correctly for staff users, remove the decorator and request again, if you go thru this time, then everything is fine, the only thing to test is then the logic inside the views.

but right now, you are getting 500 instead of 403, which means you have backend errors. fix them first

Upvotes: 1

Related Questions