Django中的csrf_token和单元测试

1、前言#####

最近在学习django,使用的书是《Python Web开发 测试驱动方法》,在第四章中遇到了一个问题使用render_to_string()函数。学习过程中使用的是py2,Django的版本是1.10.1。

2、问题描述#####

第四章的单元测试部分代码:

class HomePageTest(TestCase):
    [...]
    def test_home_page_returns_correct_html(self):
        request = HttpRequest()
        response = home_page(request)
        expected_html = render_to_string('home.html')
        self.assertEqual(response.content.decode(), expected_html)
    [...]

在没有在表单中加入CSRF令牌{% csrf_token %}时,运行都是正常的。

I:\Django_learn\superlists>python manage.py test
Creating test database for alias 'default'...
...
----------------------------------------------------------------------
Ran 3 tests in 0.000s

OK
Destroying test database for alias 'default'...

I:\Django_learn\superlists>

现在在home.html中加入CSRF令牌{% csrf_token %}后。



    To-Do lists


    

Your To-Do lists

{% csrf_token %}
{{ new_item_text }}

再次运行单元测试

I:\Django_learn\superlists>python manage.py test
Creating test database for alias 'default'...
.F.
======================================================================
FAIL: test_home_page_returns_correct_html (lists.tests.HomePageTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "I:\Django_learn\superlists\lists\tests.py", line 28, in test_home_page_returns_correct_html
    self.assertEqual(response.content.decode(), expected_html)
AssertionError: u'\n\n    To-Do lists\n\n\n    

Your To-Do lists

\n
\n \n \n
\n \n \n
\n\n\n' != u'\n\n To-Do lists\n\n\n

Your To-Do lists

\n
\n \n \n
\n \n \n
\n\n\n' ---------------------------------------------------------------------- Ran 3 tests in 0.047s FAILED (failures=1) Destroying test database for alias 'default'...

根据错误信息可以知道在最后的断言self.assertEqual(response.content.decode(), expected_html)导致测试失败。
我们添加两行用于调试,打印出response.content.decode()和expected_html.

   print 'response.content.decode()\n', response.content.decode()
   print 'expected_html\n', expected_html
I:\Django_learn\superlists>python manage.py test
Creating test database for alias 'default'...
.response.content.decode()


    To-Do lists


    

Your To-Do lists

expected_html To-Do lists

Your To-Do lists

.. ---------------------------------------------------------------------- Ran 3 tests in 0.031s OK Destroying test database for alias 'default'... I:\Django_learn\superlists>

在渲染模板时,Django 会把这个模板标签替换成一个元素,其值是CSRF 令牌。
从上面的html代码可以看出,通过视图函数home_page()渲染得到的响应包含csrf转换的元素,而render_to_string()则未生成该部分,所以导致测试失败。

3、如何解决#####

经过google,在stackoverflow找到了解决办法。
按照stackoverflow上的解决办法(当前djano==1.10.1),我使用expected_html = render_to_string('home.html', request=request)和render_to_string('index.html', context_instance=RequestContext(request))仍然会报错,于是将自己django版本降低到1.8后使用expected_html = render_to_string('home.html', request=request),测试通过。

你可能感兴趣的:(Django中的csrf_token和单元测试)