solving unittest bug of csrf_token in Django

in the Chapter 5 of Book “Test-Driven Web Development with Python” written by Harry J.W. Percival, there is a bug in the part of unit test.

while high version of Django(>1.7) rendering template, it will replace the template tag with a <input type="hidden">, the value is csrf_token.

So with the test code in the book, while running unittest, the respond taken by view functionhome_page() includes <input>element, but render_to_string() does not build up this part, contributing the fail of test.

the error message is following:

Blog: http://www.cnblogs.com/panzeyan/p/5819373.html, offers a solution, that adding request=request while calling render_to_string but only Django version from 1.8.x to 1.9.x can solve it.

As a result, my version of Django is 1.10.x, because the token value from view is different from what in the return value of render_to_string().

Until now, I cannot solve the problem with normal way, and even the writter of the book suggests that we should use version 1.8.7, for it is a long term support version.
https://groups.google.com/forum/#!topic/obey-the-testing-goat-book/fwY7ifEWKMU

But, I do not want to downdate my version of Dfango, so I devide to use an informal method, using Regular Expression to delete the tag while testing.It is not a suggested method, but you can use it in some special condition.

The code is following:

Leave a Reply

Your email address will not be published. Required fields are marked *