gpt4 book ai didi

python - CSRF token 干扰 TDD - 是否有存储 csrf 输出的变量?

转载 作者:太空狗 更新时间:2023-10-30 01:57:52 28 4
gpt4 key购买 nike

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

<input type='hidden' name='csrfmiddlewaretoken' value='hrPLKVOlhAIXmxcHI4XaFjqgEAMCTfUa' />

所以,我希望得到一个简单的答案,但我没能找到:如何呈现 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)

这是来自 views.py 的渲染:

def home_page(request):
return render(request, 'home.html', {
'new_item_text': request.POST.get('item_text'),
})

这是测试失败,当我使用 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>'

----------------------------------------------------------------------

最佳答案

从您提供的代码片段来看,您似乎正在研究“使用 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

关于python - CSRF token 干扰 TDD - 是否有存储 csrf 输出的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35582333/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com