how to disable csrf in testing django?

好久不见. 提交于 2019-12-24 17:28:48

问题


I have a problem testing views with csrf tokens.

This code

class ViewTests(TestCase):
    def test_bets_view(self):
        login_page = self.client.get('/users/login/')
        print(login_page.content)

returns HTML with CSRF hidden input.

And this thing, which I need to compare to the former HTML,

expected_html = render_to_response('login.html',
                                   dictionary={'form': LoginForm()})

doesn't have hidden CSRF input. So the assertion fails.

Ho do I disable CSRF rendering in test client?


回答1:


You should never compare the complete HTML content. Just check the functionalities. In case you need disabling the csrf at any cost, following logic should help I guess.

In your views.py file, add the following package

from django.views.decorators.csrf import csrf_exempt

Then just before the function definintion, in which you are performing your checks, add this snippet:

@csrf_exempt

This will disable the default verification of csrf. Even if your incoming request has a hidden csrf token, your server function will completely ignore it. This should do the trick of disabling the csrf.




回答2:


You can override your middleware settings in your unit test like this:

from django.test import override_settings

testing_middleware = [ ... anything but csrf middleware goes here ]


class TestWhatever(TestCase)
    @override_settings(MIDDLEWARE=testing_middleware)
    def testSomething():
        # no csrf error will occur 
        self.client.post('/', data={ ... })



回答3:


First you get the page in your tests and extract the csrf token from it:

page = self.client.get("/users/login")
token = page.context.get("csrf_token")

Then you use the same token to render the template and compare:

expected_html = TemplateResponse(
    page.wsgi_request,                                              
    "login.html",                                   
    context={"form": LoginForm(), "csrf_token": token}).render()

assert expected_html.content == page.content


来源:https://stackoverflow.com/questions/28983158/how-to-disable-csrf-in-testing-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!