簡體   English   中英

燒瓶http-auth和unittesting

[英]flask http-auth and unittesting

嗨!

我有一個使用HTTP Basic身份驗證保護的路由,由Flask-HTTPAuth實現。 如果我使用curl,一切正常(我可以訪問路線),但是當進行單元測試時,無法訪問路徑,即使我提供了正確的用戶名和密碼。

以下是我的測試模塊中的相關代碼片段:

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

以下是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

我的路線:

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

單元測試拋出以下異常:

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

我想再次強調,當我使用與我的測試客戶端提供的完全相同的參數運行curl時,一切正常,但是當我運行測試時,甚至沒有調用verify_password方法。

非常感謝您的幫助!

你會喜歡這個。

你的send方式:

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

你的delete方法:

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

請注意,您將headers作為第三個位置參數傳遞,因此它將作為data傳入send()

以下是使用pytest和內置monkeypatch夾具完成此操作的示例。

如果我在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()})

我可以創建一個返回燒瓶測試客戶端的夾具,並修補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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM