第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

從另一個(gè)服務(wù)(微服務(wù)架構(gòu))驗(yàn)證 Flask 單元測試客戶端?

從另一個(gè)服務(wù)(微服務(wù)架構(gòu))驗(yàn)證 Flask 單元測試客戶端?

問題:所以我的問題是我有一個(gè) Flask 微服務(wù)想要對其實(shí)施單元測試,所以當(dāng)我開始編寫我的測試用例時(shí),我發(fā)現(xiàn)我需要對單元測試客戶端進(jìn)行身份驗(yàn)證,因?yàn)槟承┒它c(diǎn)需要授權(quán),而整個(gè)身份驗(yàn)證的問題就出現(xiàn)了系統(tǒng)在另一個(gè)服務(wù)中該服務(wù)可以做的關(guān)于身份驗(yàn)證的所有工作是驗(yàn)證 JWT 令牌并從中獲取用戶 ID,所以這里是其中之一 views.pyfrom flask_restful import Resourcefrom common.decorators import authorizeclass PointsView(Resource):    decorators = [authorize]    def get(self, user):        result = {"points": user.active_points}        return result并授權(quán)裝飾者來自 decorators.pyimport flaskimport jwtfrom jwt.exceptions import DecodeError, InvalidSignatureErrorfrom functools import wrapsfrom flask import requestfrom flask import current_app as appfrom app import dbfrom common.models import Userfrom common.utils import generate_error_responsedef authorize(f):    """This decorator for validate the logged in user """    @wraps(f)    def decorated_function(*args, **kwargs):        if 'Authorization' not in request.headers:            return "Unable to log in with provided credentials.", 403        raw_token = request.headers.get('Authorization')        if raw_token[0:3] != 'JWT':            return generate_error_response("Unable to log in with provided credentials.", 403)        token = str.replace(str(raw_token), 'JWT ', '')        try:            data = jwt_decode_handler(token)        except (DecodeError, InvalidSignatureError):            return generate_error_response("Unable to log in with provided credentials.", 403)        user = User.query.filter_by(id=int(data['user_id'])).first()        return f(user, *args, **kwargs)    return decorated_function和測試用例來自 tests.pyimport unittestfrom app import create_app, dbfrom common.models import Userclass TestMixin(object):    """    Methods to help all or most Test Cases    """    def __init__(self):        self.user = None我的身份驗(yàn)證系統(tǒng)的工作方式如下:任何服務(wù)(包括這個(gè))請求用戶服務(wù)來獲取用戶 JWT 令牌任何服務(wù)都將 JWT 令牌解碼并從中獲取用戶 ID通過他的ID從數(shù)據(jù)庫中獲取用戶對象所以我不知道如何在測試用例中進(jìn)行身份驗(yàn)證。
查看完整描述

2 回答

?
茅侃侃

TA貢獻(xiàn)1842條經(jīng)驗(yàn) 獲得超21個(gè)贊

這里只是一個(gè)例子。我跳過了一些小東西,例如create_app,jwt.decode(token)等等。我相信你能理解主要方法。結(jié)構(gòu):


src

├── __init__.py # empty

├── app.py

└── auth_example.py

應(yīng)用程序.py:


from flask import Flask


from src.auth_example import current_identity, authorize


app = Flask(__name__)



@app.route('/')

@authorize()

def main():

    """

    You can use flask_restful - doesn't matter

    Do here all what you need:

        user = User.query.filter_by(id=int(current_identity['user_id'])).first()

        etc..

    just demo - return current user_id

    """


    return current_identity['user_id']

auth_example.py :


from flask import request, _request_ctx_stack

from functools import wraps

from werkzeug.local import LocalProxy


current_identity = LocalProxy(lambda: getattr(_request_ctx_stack.top, 'current_identity', None))



def jwt_decode_handler(token):

    """

    just do here all what you need. Should return current user data

    :param str token:

    :return: dict

    """

    # return jwt.decode(token), but now - just demo

    raise Exception('just demo')



def authorize():

    def _authorize(f):


        @wraps(f)

        def __authorize(*args, **kwargs):

            if 'Authorization' not in request.headers:

                return "Unable to log in with provided credentials.", 403


            raw_token = request.headers.get('Authorization')

            if raw_token[0:3] != 'JWT':

                return "Unable to log in with provided credentials.", 403

            token = str.replace(str(raw_token), 'JWT ', '')

            try:

                # I don't know do you use Flask-JWT or not

                # this is doesn't matter - all what you need is just to mock jwt_decode_handler result 

                _request_ctx_stack.top.current_identity = jwt_decode_handler(token)

            except Exception:

                return "Unable to log in with provided credentials.", 403


            return f(*args, **kwargs)


        return __authorize

    return _authorize

我們的測試:


import unittest


from mock import patch


from src.app import app


app.app_context().push()



class TestExample(unittest.TestCase):


    def test_main_403(self):

        # just a demo that @authorize works fine

        result = app.test_client().get('/')

        self.assertEqual(result.status_code, 403)


    def test_main_ok(self):

        expected = '1'

        # we say that jwt_decode_handler will return {'user_id': '1'}

        patcher = patch('src.auth_example.jwt_decode_handler', return_value={'user_id': expected})

        patcher.start()

        result = app.test_client().get(

            '/',

            # send a header to skip errors in the __authorize

            headers={

                'Authorization': 'JWT=blabla',

            },

        )

        # as you can see current_identity['user_id'] is '1' (so, it was mocked in view)

        self.assertEqual(result.data, expected)

        patcher.stop()

因此,在您的情況下,您只需要 mock jwt_decode_handler。另外我建議不要在裝飾器中添加任何額外的參數(shù)。當(dāng)您有兩個(gè)以上具有不同參數(shù)、遞歸、硬處理等的裝飾器時(shí),將很難調(diào)試。


希望這可以幫助。


查看完整回答
反對 回復(fù) 2022-01-05
?
侃侃爾雅

TA貢獻(xiàn)1801條經(jīng)驗(yàn) 獲得超16個(gè)贊

您能否在您的單元測試框架中創(chuàng)建一些模擬令牌(您的裝飾器實(shí)際上可以像在真實(shí)請求中一樣解碼)并將它們與您的測試客戶端一起發(fā)送?可以在此處查看其外觀示例:https : //github.com/vimalloc/flask-jwt-extended/blob/master/tests/test_view_decorators.py#L321


查看完整回答
反對 回復(fù) 2022-01-05
  • 2 回答
  • 0 關(guān)注
  • 227 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號