Python语言与信息数据获取和机器学习Python 运维我的Python自学之路

Django中的csrf_token和单元测试

2017-02-16  本文已影响135人  嘿嘿_小于同学
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 %}后。

<html>
<head>
    <title>To-Do lists</title>
</head>
<body>
    <h1>Your To-Do lists</h1>
    <form method="POST">
        <input name="item_text" id="id_new_item" placeholder="Enter a to-do item"/>
        {% csrf_token %}
    </form>
    <table id="id_list_table">
        <tr><td>{{ new_item_text }}</td></tr>
        </table>
</body>
</html>

再次运行单元测试

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'<html>\n<head>\n    <title>To-Do lists</title>\n</head>\n<body>\n    <h1>Your To-Do lists</h1>\n    <form method="POST">\n        <input name="item_text" id="id_new_item" placeholder="Enter a to-do item"/>\n        <input type=\'hidden\' name=\'csrfmiddlewaretoken\' value=\'WkE5AMVHQu5oVmJ6wFSU2KjMvXV6yGYwsB3IJ0Too0QM4xXKVPj6BJ24DBLP600v\' />\n    </form>\n    <table id="id_list_table">\n        <tr><td></td></tr>\n        </table>\n</body>\n</html>\n' != u'<html>\n<head>\n    <title>To-Do lists</title>\n</head>\n<body>\n    <h1>Your To-Do lists</h1>\n    <form method="POST">\n        <input name="item_text" id="id_new_item" placeholder="Enter a to-do item"/>\n        \n    </form>\n    <table id="id_list_table">\n        <tr><td></td></tr>\n        </table>\n</body>\n</html>\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()
<html>
<head>
    <title>To-Do lists</title>
</head>
<body>
    <h1>Your To-Do lists</h1>
    <form method="POST">
        <input name="item_text" id="id_new_item" placeholder="Enter a to-do item"/>
        <input type='hidden' name='csrfmiddlewaretoken' value='VUMXA6dNnUT8Y2rAY3nAcQyTMtJKGznXqts0HbPaDWN16b4uiMDkFMWp1EVbC3xu' />
    </form>
    <table id="id_list_table">
        <tr><td></td></tr>
        </table>
</body>
</html>

expected_html
<html>
<head>
    <title>To-Do lists</title>
</head>
<body>
    <h1>Your To-Do lists</h1>
    <form method="POST">
        <input name="item_text" id="id_new_item" placeholder="Enter a to-do item"/>

    </form>
    <table id="id_list_table">
        <tr><td></td></tr>
        </table>
</body>
</html>

..
----------------------------------------------------------------------
Ran 3 tests in 0.031s

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

I:\Django_learn\superlists>

在渲染模板时,Django 会把这个模板标签替换成一个<input type="hidden">元素,其值是CSRF 令牌。
从上面的html代码可以看出,通过视图函数home_page()渲染得到的响应包含csrf转换的<input>元素,而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),测试通过。

上一篇下一篇

猜你喜欢

热点阅读