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

All*_*Lin 5 python iis wsgi flask

我正在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'
Run Code Online (Sandbox Code Playgroud)

我的视图中处理“ REMOTE_USER”的部分类似:

cf = CashFlow(...,
              user=request.environ.get('REMOTE_USER'),
              ...)
db.session.add(cf)
Run Code Online (Sandbox Code Playgroud)

All*_*Lin 5

Flask应用程序单元测试的设置(模拟)请求标头中找出我自己问题的答案。有一个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'
Run Code Online (Sandbox Code Playgroud)