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

标签 python unit-testing session flask

我很难设置测试 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/

相关文章:

python - ipysheets修改布局: wrap text,列宽

c - 寻求关于C的自动化测试框架的建议

php - 您可以在回调中使用 $this 来获取 phpunit 中模拟类的 protected 属性吗?

javascript - 当浏览器关闭时,是否有一种可靠的方法来注销用户?

java - 身份验证过滤器无法正确识别身份验证

python - CNN 模型比 CNN-SVM 组合模型具有更好的精度

python - Scrapy - 选择除第一个之外的所有具有相同类别的表

Django 签名 cookie session 存储、重放攻击和 SESSION_COOKIE_AGE

python - Matplotlib 中的一半或四分之一极 map ?

javascript - Chai(如 promise 的那样)匹配属性(property)