(Flask)伪造request.environ ['REMOTE_USER']进行测试

时间:2015-12-22 14:53:30

标签: python iis flask wsgi

我正在IIS上部署Flask应用并使用其Windows身份验证,如果成功通过身份验证,则会将request.environ ['REMOTE_USER']设置为您的Windows用户名。现在编写测试用例时,如何伪造request.environ ['REMOTE_USER']?测试用例独立于IIS服务器运行。

我的尝试:

from flask import request

def test_insert_cash_flow_through_post(self):
    """Test that you can insert a cash flow through post."""
    request.environ['REMOTE_USER'] = 'foo'
    self.client.post("/index?account=main",
                     data=dict(settlement_date='01/01/2016',
                               transaction_type='Other',
                               certainty='Certain',
                               transaction_amount=1))
    assert CashFlow.query.first().user == 'foo'

处理'REMOTE_USER'的视图部分类似于:

cf = CashFlow(...,
              user=request.environ.get('REMOTE_USER'),
              ...)
db.session.add(cf)

2 个答案:

答案 0 :(得分:5)

Setting (mocking) request headers for Flask app unit test找出我自己问题的答案。您可以将请求环境变量传递到environ_base参数。它记录在werkzeug.test.EnvironBuilder

    def test_insert_cash_flow_through_post(self):
    """Test that you can insert a cash flow through post."""
    assert not CashFlow.query.first()
    self.client.post("/index?account=main",
                     environ_base={'REMOTE_USER': 'foo'},
                     data=dict(settlement_date='01/01/2016',
                               transaction_type='Other',
                               certainty='Certain',
                               transaction_amount=1))
    assert CashFlow.query.first().user == 'foo'

答案 1 :(得分:0)

你不必假装它。您可以在测试中进行设置。

from flask import request

def test_something():
    request.environ['REMOTE_USER'] = 'some user'
    do_something_with_remote_user()
    del request.environ['REMOTE_USER']

如果您担心保留可能已设置的任何值,您也可以轻松地执行此操作。

def test_something():
    original_remote_user = request.environ.get('REMOTE_USER')
    do_something_with_remote_user()
    request.environ['REMOTE_USER'] = original_remote_user

您也可以在更高的范围内处理此问题,但如果不知道测试的结构,则很难告诉您如何执行此操作。