我正在学习如何使用Mock在Python中测试函数。我正在试着为一个简单的函数写一个测试,
@social.route('/friends', methods=['GET', 'POST'])
def friends():
test_val = session.get('uid')
if test_val is None:
return redirect(url_for('social.index'))
else:
return render_template("/home.html")然而,我被困在如何尝试模拟session.get('uid')值的问题上。到目前为止,这是我的尝试,
@patch('session', return_value='')
@patch('flask.templating._render', return_value='')
def test_mocked_render(self, mocked, mock_session):
print "mocked", repr(self.app.get('/social/friends').data)
print "was _render called?", mocked.called这种尝试可能是完全错误的,这肯定是错误的方式,因为我仍然不能模拟会话。但是,有没有人能指导我正确地完成这件事?谢谢。
发布于 2016-04-09 19:11:35
从Flask 0.8开始,我们提供了一个所谓的“会话事务”,它模拟了在测试客户端的上下文中打开会话并对其进行修改的适当调用。
让我们举一个简单的例子:app.py
from flask import Flask, session
app = Flask(__name__)
app.secret_key = 'very secret'
@app.route('/friends', methods=['GET', 'POST'])
def friends():
test_val = session.get('uid')
if test_val is None:
return 'uid not in session'
else:
return 'uid in session'
if __name__ == '__main__':
app.run(debug=True)测试文件:test_app.py
import unittest
from app import app
class TestSession(unittest.TestCase):
def test_mocked_session(self):
with app.test_client() as c:
with c.session_transaction() as sess:
sess['uid'] = 'Bar'
# once this is reached the session was stored
rv = c.get('/friends')
assert rv.data == 'uid in session'
if __name__ == '__main__':
unittest.main()通过python test_app.py运行测试。
文档:Accessing and Modifying Sessions
https://stackoverflow.com/questions/36509662
复制相似问题