代码之家  ›  专栏  ›  技术社区  ›  titiree

烧瓶-带鼻的单元测试

  •  1
  • titiree  · 技术社区  · 7 年前

    我正试着用nose测试下面的代码。app.py文件如下:

    from flask import Flask, session, redirect, url_for, request
    
    app = Flask(__name__)
    
    @app.route('/')
    def index():
        session['key'] = 'value'
        print('>>>> session:', session)
        return redirect(url_for("game"))
    

    测试文件如下:

    from nose.tools import *
    from flask import session
    from app import app
    
    app.config['TESTING'] = True
    web = app.test_client()
    
    def test_index():
    
        with app.test_request_context('/'):
            print('>>>>test session:', session)
            assert_equal(session.get('key'), 'value')
    

    当我运行测试文件时,我得到一个断言错误 None != 'value' 测试文件中的print语句打印空会话对象。此外,app.py文件中的print语句不会打印任何内容。这是否意味着索引函数没有运行?

    为什么会这样?根据烧瓶文件( http://flask.pocoo.org/docs/1.0/testing/#other-testing-tricks ) 我应该可以通过test_request_context()访问会话内容。

    另外,如果我像这样编写test_index函数,测试也会正常工作(app.py和测试文件中的print语句都会执行):

    def test_index():
    
        with app.test_client() as c:
            rv = c.get('/')
            print('>>>>test session:', session)
            assert_equal(session.get('key'), 'value')
    

    在“with”语句中使用flask.test_client()和flask.test_request_上下文有什么区别?据我所知,两者的重点都是让请求上下文保持更长的时间。

    1 回复  |  直到 7 年前
        1
  •  1
  •   clockwatcher    7 年前

    你只是在设置你的请求上下文。实际上,你需要让你的应用程序发出请求,让任何事情发生——就像你的完整客户端中的c.get()一样。

    试试下面,我想你会有更好的运气:

    def test_index():
    
        with app.test_request_context('/'):
            app.dispatch_request()
            print('>>>>test session:', session)
            assert_equal(session.get('key'), 'value')