烧瓶 - 用鼻子进行单元测试

时间:2018-06-14 22:28:54

标签: python python-3.x flask nose

我试图用鼻子测试下面的代码。 app.py文件如下:

vc = PopoverViewController()

测试文件如下:

if let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "PopoverViewController") as? PopoverViewController {
    vc.modalPresentationStyle = .popover
    let popover = vc.popoverPresentationController!
    popover.delegate = self
    popover.permittedArrowDirections = .right
    vc.popoverPresentationController?.sourceView = sender
    vc.popoverPresentationController?.sourceRect = sender.bounds                        
    self.present(vc, animated: true, completion: nil)
}

运行测试文件时,出现断言错误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")) 并且测试文件中的print语句打印一个空的会话对象。此外,app.py文件中的print语句不会打印任何内容。这是否意味着索引功能没有运行?

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

此外,如果我改为编写test_index函数,测试工作(并且app.py和测试文件中的两个print语句都被执行):

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

在'中使用Flask.test_client()和Flask.test_request_context有什么区别?声明?据我了解,两者的关键是要保持请求上下文更长时间。

1 个答案:

答案 0 :(得分:1)

您只是设置请求上下文。您需要实际让您的应用程序发送请求才能发生任何事情 - 类似于您的完整客户端中的c.get()。

尝试以下内容,我认为你会有更好的运气:

def test_index():

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