gpt4 book ai didi

python - 在测试中使用 url_for

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

我正在为 Flask 应用程序编写一些测试,遇到一个问题,即我的 test_client 响应中的 URL 与从测试用例中调用 url_for 生成的 URL 不匹配。例如,我的模板中有以下内容:

<li><a href="#" onClick="requestReport('{{ url_for('report') }}', '{{ session['email'] }}');">Report</a></li>

来自 test_client 的响应呈现为:

<li><a href="#" onClick="requestReport('/api/report', 'user@domain.com');">Report</a></li>

我有一个测试用例,用于检查以确保此 URL 在特定条件下出现在页面上:

self.client = self.app.test_client(use_cookies=True)
with self.app.app_context():
page = self.client.get(url_for("index"), follow_redirects=True).data.decode()
assert url_for("report") in page

问题是,即使 URL 出现在页面上,此测试也会失败,因为模板中的 url_for 调用产生的输出与我的测试用例中的 url_for 调用产生的输出不同。如果我从测试用例代码中打印 url_for("report"),我会得到:

http://localhost:5000/api/report

我将 app.config 中的 SERVER_NAME 键设置为“localhost:5000”,因为如果我没有设置 SERVER_NAME,测试用例代码将抛出此错误:

RuntimeError: Application was not able to create a URL adapter for request independent URL generation. You might be able to fix this by setting the SERVER_NAME config variable.

显然,我可以通过在测试用例代码中对 URL 进行硬编码来解决这个问题,但我更愿意使用 URL_for,这样以后对 URL 的更改就不会破坏我的测试代码。

我已经尝试了几个不同的字符串作为 SERVER_NAME,包括“”,它只是生成一个格式错误的 URL,仍然与响应中生成的不匹配。

除了对 URL 进行硬编码之外,还有什么方法可以解决这个问题吗?

最佳答案

对于API测试,可以使用test_request_context

class TestFlaskApi(unittest.TestCase):                                          
def setUp(self):
self.app = create_app()
self.app_context = self.app.test_request_context()
self.app_context.push()
self.client = self.app.test_client()

def test_hello(self):
response = self.client.get(url_for('api.hello'),
content_type='text')

self.assertEqual(response.get_data(as_text=True), 'hello')

关于python - 在测试中使用 url_for,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41065584/

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