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>'
----------------------------------------------------------------------
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: