Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CRSF Token Interfering With TDD - Is there a variable that stores csrf output?

So, I kept returning a Failing test in Django when comparing expected to actual html with form input, so I printed out the result and realized the difference was the rather simple line, caused by my {% csrf_token %}, as follows:

<input type='hidden' name='csrfmiddlewaretoken' value='hrPLKVOlhAIXmxcHI4XaFjqgEAMCTfUa' />

So, I expect a simple answer, but I haven't been able to find it: How do I render the result of a csrf_token for use in testing?

Here's the Test setup and failure:

def test_home_page_returns_correct_html_with_POST(self):
        request = HttpRequest()
        request.method = 'POST'
        request.POST['item_text'] = 'A new list item'

        response = home_page(request)

        self.assertIn('A new list item', response.content.decode())

        expected_html = render_to_string(
        'home.html',
        {'new_item_text': 'A new list item'},
******this is where I'm hoping for a simple one-line mapping******

    )
    self.assertEqual(response.content.decode(), expected_html)

Here's the rendering from views.py:

def home_page(request):
    return render(request, 'home.html', {
        'new_item_text': request.POST.get('item_text'),
    })

And here's the test failure, when I run the test with python manage.py test

FAIL: test_home_page_returns_correct_html_with_POST (lists.tests.HomePageTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\Me\PycharmProjects\superlists\lists\tests.py", line 29, in test_home_page_returns_correct_html_with_POST
    self.assertEqual(response.content.decode(), expected_html)
AssertionError: '<!DO[298 chars]     <input type=\'hidden\' name=\'csrfmiddlew[179 chars]tml>' != '<!DO[298 chars]     \n    </form>\n\n    <table
 id="id_list_t[82 chars]tml>'

----------------------------------------------------------------------
like image 337
Jordon Birk Avatar asked Feb 23 '16 16:02

Jordon Birk


People also ask

What is{% CSRF_ token%}?

csrf_token. Django has a {% csrf_token %} tag that is implemented to avoid malicious attacks. It generates a token on the server-side when rendering the page and makes sure to cross-check this token for any requests coming back in. If the incoming requests do not contain the token, they are not executed.

What is CSRF token mismatch?

The “Invalid or missing CSRF token” message means that your browser couldn't create a secure cookie or couldn't access that cookie to authorize your login. This can be caused by ad- or script-blocking plugins or extensions and the browser itself if it's not allowed to set cookies.

How is CSRF token generated?

The CSRF token values contain significant entropy and are unpredictable since the generated tokens use a pseudo-random number generator, a static secret, and a seeded timestamp. In addition to this, tokens are different for each user and are stored only for an active user session.


1 Answers

Judging by the code snippet you provided, it seems you are working through the examples from the book "Test Driven Development with Python", but are not using Django 1.8.

This post from the book's Google Groups discussion addresses the test failure, as you are experiencing it:

https://groups.google.com/forum/#!topic/obey-the-testing-goat-book/fwY7ifEWKMU/discussion

And this GitHub issue (from the book's official repository) describes a fix consistent with your question:

https://github.com/hjwp/book-example/issues/8

like image 174
Jose Nario Avatar answered Sep 30 '22 11:09

Jose Nario