gpt4 book ai didi

python - 无法在 Flask 单元测试中设置 session 变量

转载 作者:太空宇宙 更新时间:2023-11-04 07:35:59 25 4
gpt4 key购买 nike

我很难设置测试 session 变量来对某些 Flask View 进行单元测试。通常通过处理 Google Oauth2 登录内容的代码设置“电子邮件”和“显示名称” session 变量。我的目标是让单元测试工具设置这些 session 变量。这样,我的 Flask 端点就可以独立于整个 oauth2 业务进行测试。

这是我到目前为止尝试过的方法。我写了一个单独的“数字增量器”迷你项目来隔离问题。这是运行单元测试的堆栈跟踪。

Error
Traceback (most recent call last):
File "/home/myusername/PycharmProjects/FlaskTestingStuff/MyFlaskTest.py", line 12, in testNumberIncrease
self.assertTrue(res is not None)
File "/usr/lib/python3.4/contextlib.py", line 66, in __exit__
next(self.gen)
File "/usr/local/lib/python3.4/dist-packages/flask/testing.py", line 94, in session_transaction
self.cookie_jar.extract_wsgi(c.request.environ, headers)
File "/usr/local/lib/python3.4/dist-packages/flask/ctx.py", line 386, in __exit__
self.auto_pop(exc_value)
File "/usr/local/lib/python3.4/dist-packages/flask/ctx.py", line 374, in auto_pop
self.pop(exc)
File "/usr/local/lib/python3.4/dist-packages/flask/ctx.py", line 341, in pop
self.app.do_teardown_request(exc)
File "/usr/local/lib/python3.4/dist-packages/flask/app.py", line 1710, in do_teardown_request
bp = _request_ctx_stack.top.request.blueprint
AttributeError: 'NoneType' object has no attribute 'request'

这是我的数字递增“迷你项目” flask 应用程序的 View 。

from flask import Flask, session, request

app = Flask(__name__)
app.secret_key = "somedumbkey"

@app.route("/increasenum", methods=["GET"])
def increase_num():
if session and "last_num" in session:
num = session["last_num"]
num = str(int(num) + 1)
session["last_num"] = num
return num
else:
session["last_num"] = "0"
return "0"

if __name__ == '__main__':
app.run(debug=True)

最后,这是让我很难过的单元测试。

import unittest
from flaskapp import app
from flask import session

class FlaskTestCase(unittest.TestCase):

def testNumberIncrease(self):
with app.test_client() as client:
with client.session_transaction() as sess:
sess["last_num"] = "8"
res = client.get("/increasenum")
self.assertTrue(res is not None)

if __name__ == '__main__':
unittest.main()

是否有人对如何为这些类型的单元测试正确设置“模拟 session 变量”有任何想法?

最佳答案

缩进错误。 session 应在 session_transaction() block 中修改,但请求应在该 block 结束后发送。取消缩进一级 res = client.get()

import unittest
from flaskapp import app
from flask import session

class FlaskTestCase(unittest.TestCase):
def testNumberIncrease(self):
with app.test_client() as client:
with client.session_transaction() as sess:
# Modify the session in this context block.
sess["last_num"] = "8"
# Test the request in this context block.
res = client.get("/increasenum")
self.assertTrue(res is not None)

if __name__ == '__main__':
unittest.main()

关于python - 无法在 Flask 单元测试中设置 session 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35470357/

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