简体   繁体   English

烧瓶http-auth和unittesting

[英]flask http-auth and unittesting

Hi! 嗨!

I have a route that I have protected using HTTP Basic authentication, which is implemented by Flask-HTTPAuth. 我有一个使用HTTP Basic身份验证保护的路由,由Flask-HTTPAuth实现。 Everything works fine (i can access the route) if i use curl, but when unit testing, the route can't be accessed, even though i provide it with the right username and password. 如果我使用curl,一切正常(我可以访问路线),但是当进行单元测试时,无法访问路径,即使我提供了正确的用户名和密码。

Here are the relevant code snippets in my testing module: 以下是我的测试模块中的相关代码片段:

class TestClient(object):
    def __init__(self, app):
        self.client = app.test_client()

    def send(self, url, method, data=None, headers={}):
        if data:
            data = json.dumps(data)

        rv = method(url, data=data, headers=headers)
        return rv, json.loads(rv.data.decode('utf-8'))

    def delete(self, url, headers={}):
        return self.send(url, self.client.delete, headers)

class TestCase(unittest.TestCase):
    def setUp(self):
        app.config.from_object('test_config')
        self.app = app
        self.app_context = self.app.app_context()
        self.app_context.push()
        db.create_all()
        self.client = TestClient(self.app)

    def test_delete_user(self):
        # create new user
        data = {'username': 'john', 'password': 'doe'}
        self.client.post('/users', data=data)

        # delete previously created user
        headers = {}
        headers['Authorization'] = 'Basic ' + b64encode((data['username'] + ':' + data['password'])
                                                        .encode('utf-8')).decode('utf-8')
        headers['Content-Type'] = 'application/json'
        headers['Accept'] = 'application/json'
        rv, json = self.client.delete('/users', headers=headers)
        self.assertTrue(rv.status_code == 200) # Returns 401 instead

Here are the callback methods required by Flask-HTTPAuth: 以下是Flask-HTTPAuth所需的回调方法:

auth = HTTPBasicAuth()

@auth.verify_password
def verify_password(username, password):
    # THIS METHOD NEVER GETS CALLED
    user = User.query.filter_by(username=username).first()
    if not user or not user.verify_password(password):
        return False
    g.user = user
    return True

@auth.error_handler
def unauthorized():
    response = jsonify({'status': 401, 'error': 'unauthorized', 'message': 'Please authenticate to access this API.'})
    response.status_code = 401
    return response

Any my route: 我的路线:

@app.route('/users', methods=['DELETE'])
@auth.login_required
def delete_user():
    db.session.delete(g.user)
    db.session.commit()
    return jsonify({})

The unit test throws the following exception: 单元测试抛出以下异常:

Traceback (most recent call last):
  File "test_api.py", line 89, in test_delete_user
    self.assertTrue(rv.status_code == 200) # Returns 401 instead
AssertionError: False is not true

I want to emphazise once more that everything works fine when i run curl with exactly the same arguments i provide for my test client, but when i run the test, verify_password method doesn't even get called. 我想再次强调,当我使用与我的测试客户端提供的完全相同的参数运行curl时,一切正常,但是当我运行测试时,甚至没有调用verify_password方法。

Thank you very much for your help! 非常感谢您的帮助!

You are going to love this. 你会喜欢这个。

Your send method: 你的send方式:

def send(self, url, method, data=None, headers={}):
    pass

Your delete method: 你的delete方法:

def delete(self, url, headers={}):
    return self.send(url, self.client.delete, headers)

Note you are passing headers as third positional argument, so it's going as data into send() . 请注意,您将headers作为第三个位置参数传递,因此它将作为data传入send()

Here is an example how this could be done with pytest and the inbuilt monkeypatch fixture. 以下是使用pytest和内置monkeypatch夹具完成此操作的示例。

If I have this API function in some_flask_app : 如果我在some_flask_app有这个API函数:

from flask_httpauth import HTTPBasicAuth

app = Flask(__name__)
auth = HTTPBasicAuth()

@app.route('/api/v1/version')
@auth.login_required
def api_get_version():
    return jsonify({'version': get_version()})

I can create a fixture that returns a flask test client and patches the authenticate function in HTTPBasicAuth to always return True : 我可以创建一个返回烧瓶测试客户端的夹具,并修补HTTPBasicAuth中的authenticate函数以始终返回True

import pytest
from some_flask_app import app, auth

@pytest.fixture(name='client')
def initialize_authorized_test_client(monkeypatch):
    app.testing = True
    client = app.test_client()
    monkeypatch.setattr(auth, 'authenticate', lambda x, y: True)
    yield client
    app.testing = False


def test_settings_tracking(client):
    r = client.get("/api/v1/version")
    assert r.status_code == 200

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我正在重组Flask-restful应用程序,但无法放置HTTP-auth以使应用程序运行 - I am restructuring my Flask-restful app, but having trouble placing the HTTP-auth in order to get app running Flask Basic HTTP Auth使用登录页面 - Flask Basic HTTP Auth use login page 使用Flask-SocketIO与Flask-Login和HTTP Basic Auth - Using Flask-SocketIO with Flask-Login and HTTP Basic Auth 如何使用Selenium向ChromeDriver提交HTTP身份验证(Flask BASIC Auth) - How to submit HTTP authentication (Flask BASIC Auth) with Selenium to ChromeDriver 在烧瓶中使用 HTTP 身份验证时的标准 401 响应 - Standard 401 response when using HTTP auth in flask flask:进行单元测试时,request.authorization始终为None - flask: When unittesting, request.authorization is always None Python FLASK REST 身份验证 - Python FLASK REST AUTH 是否可以将Flask-Login的身份验证用作REST API的简单HTTP身份验证? - Is it possible to use Flask-Login's authentication as simple HTTP auth for a REST API? 如何使用Flask HTTP Auth为Web服务实现“不正确的用户名/密码”提示? - How to implement “Incorrect username/password” hint for a webservice using Flask HTTP Auth? 烧瓶不使用curl auth - Flask not using curl auth
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM