简体   繁体   English

无法获得烧瓶单元测试中设置的会话变量

[英]Can't Get Session Variables Set Up In Flask Unit Test

I am having a difficult time setting test session variables for unit testing some Flask views. 我很难设置测试会话变量以对一些Flask视图进行单元测试。 There are "email" and "display name" session variables that are normally set via code that handles Google Oauth2 login stuff. 通常通过处理Google Oauth2登录内容的代码来设置“电子邮件”和“显示名称”会话变量。 My goal is to let the unit testing tools set those session variables instead. 我的目标是让单元测试工具设置这些会话变量。 That way, my Flask endpoints can be tested independently of the whole oauth2 business. 这样,我的Flask端点可以独立于整个oauth2业务进行测试。

Here's what I've tried so far. 到目前为止,这是我尝试过的。 I wrote a separate "number incrementer" mini-project to isolate the issue. 我编写了一个单独的“数字增量器”微型项目来隔离问题。 Here's the stack trace from running the unit test. 这是运行单元测试的堆栈跟踪。

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'

Here's the view for my number incrementing "mini project" flask app. 这是我的数字递增“ mini project”烧瓶应用程序的视图。

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)

Lastly, here is the unit test that's giving me a hard time. 最后,这是单元测试,这让我很难受。

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

Does anybody have any ideas on how to properly set up "mock session variables" properly for these kinds of unit tests? 是否有人对如何为此类单元测试正确设置“模拟会话变量”有任何想法?

The indentation is wrong. 缩进是错误的。 The session should be modified in the session_transaction() block, but the request should be sent after that block has ended. 应该在session_transaction()块中修改会话,但是应该在该块结束后发送请求。 Unindent res = client.get() by one level. 缩进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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM