CRSF令牌干扰TDD - 是否存在存储csrf输出的变量?

Jor*_*irk 4 python django tdd csrf django-csrf

因此,我在Django中返回一个失败测试,​​当时将预期与实际html与表单输入进行比较,因此我打印出结果并意识到差异是由我引起的相当简单的行,{% csrf_token %}如下所示:

<input type='hidden' name='csrfmiddlewaretoken' value='hrPLKVOlhAIXmxcHI4XaFjqgEAMCTfUa' />
Run Code Online (Sandbox Code Playgroud)

所以,我希望得到一个简单的答案,但我无法找到它:如何渲染csrf_token的结果用于测试?

这是测试设置和失败:

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)
Run Code Online (Sandbox Code Playgroud)

这是来自views.py的渲染:

def home_page(request):
    return render(request, 'home.html', {
        'new_item_text': request.POST.get('item_text'),
    })
Run Code Online (Sandbox Code Playgroud)

当我运行测试时,这是测试失败 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>'

----------------------------------------------------------------------
Run Code Online (Sandbox Code Playgroud)

Jos*_*rio 5

根据您提供的代码片段来判断,您似乎正在阅读"使用Python进行测试驱动开发"一书中的示例,但未使用Django 1.8.

本书的Google网上论坛讨论中的这篇文章解决了测试失败的问题,正如您所遇到的那样:

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

这个GitHub问题(来自本书的官方存储库)描述了与您的问题一致的修复:

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