无法在Flask单元测试中设置会话变量

时间:2016-02-18 00:12:52

标签: python unit-testing session flask

我很难设置测试会话变量来测试一些Flask视图。有“电子邮件”和“显示名称”会话变量通常通过处理Google Oauth2登录内容的代码设置。我的目标是让单元测试工具设置这些会话变量。这样,我的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'

这是我的号码递增“迷你项目”烧瓶应用程序的视图。

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()

对于如何正确设置这些单元测试的“模拟会话变量”,有没有人有任何想法?

1 个答案:

答案 0 :(得分:7)

缩进是错误的。应在session_transaction()块中修改会话,但应在该块结束后发送请求。 Unindent 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()