python – (Flask)伪造request.environ [‘REMOTE_USER’]进行测试

我正在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)

解决方法:

Setting (mocking) request headers for Flask app unit test中找出了我自己的问题的答案.有一个’environ_base’参数,您可以将请求环境变量传递到.

    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'
上一篇:Urllib和并发 – Python


下一篇:在Anaconda内部的Python上使用mod_wsgi配置Django时出错:“ImportError:没有名为django.core.wsgi的模块”