【问题标题】:How to mock HTTP authentication in Flask for testing?如何在 Flask 中模拟 HTTP 身份验证以进行测试?
【发布时间】:2015-06-22 16:32:59
【问题描述】:

我只是为我的 Flask 应用程序设置了 HTTP 身份验证,但我的测试被破坏了。如何模拟request.authentication 以再次通过测试?

这是我的代码。

server_tests.py

def test_index(self):
    res = self.app.get('/')

    self.assertTrue('<form' in res.data)
    self.assertTrue('action="/upload"' in res.data)
    self.assertEquals(200, res.status_code)

server.py

def check_auth(username, password):
    """This function is called to check if a username /
    password combination is valid.
    """
    return username == 'fusiontv' and password == 'fusiontv'

def authenticate():
    """Sends a 401 response that enables basic auth"""
    return Response(
    'Could not verify your access level for that URL.\n'
    'You have to login with proper credentials', 401,
    {'WWW-Authenticate': 'Basic realm="Login Required"'})

def requires_auth(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        auth = request.authorization
        if not auth or not check_auth(auth.username, auth.password):
            return authenticate()
        return f(*args, **kwargs)
    return decorated

@app.route("/")
@requires_auth
def index():
    return render_template('index.html')

【问题讨论】:

    标签: python unit-testing mocking pytest


    【解决方案1】:

    参考How do I mock dependencies of the views module of my Flask application in flask-testing?,你可以通过导入链来模拟它。

    假设server_tests 导入application 导入server,您可能想要这样的东西:

    server_tests.py

    def setUp(self):
        application.server.request.authorization = MagicMock(return_value=True)
    

    【讨论】:

      猜你喜欢
      • 2017-05-05
      • 2016-08-12
      • 2016-12-19
      • 2011-08-08
      • 1970-01-01
      • 1970-01-01
      • 2019-12-28
      • 2010-12-30
      • 2014-02-25
      相关资源
      最近更新 更多