1
フラスコのアプリにflask_login拡張機能を使用してログインしています。あなたが知っておく必要があるので、この拡張にはcurrent_userを格納する変数があります。コードはテストを除いて完全に動作しています。flask_login - current_user
私は(unittestのを使用して)、コードをテストしていたとき、私は「テストユーザー」を登録し、それを記録。しかしCURRENT_USER変数は、ログインしているユーザーを保持しません。
ここれます私のアプリケーションコード。カテゴリに追加一部(CURRENT_USERは、ユーザーのログイン時に設定されます):ここで
def post(self):
# Get the access token from the header
auth_header = request.headers.get('Authorization')
access_token = auth_header.split(" ")[1]
if access_token:
# Attempt to decode the token and get the User ID
user_id = User.decode_token(access_token)
if not isinstance(user_id, str):
# Go ahead and handle the request, the user is authenticated
data = request.get_json()
if data['name']:
category = Category(name = data['name'], user_id = user_id)
db.session.add(category)
db.session.commit()
response = {'id' : category.id,
'category_name' : category.name,
'created_by' : current_user.first_name
}
return response
else:
# user is not legit, so the payload is an error message
message = user_id
response = {
'message': message
}
return response
アプリをテストする私のコードです:
import unittest
import os
import json
import app
from app import create_app, db
class CategoryTestCase(unittest.TestCase):
"""This class represents the Category test case"""
def setUp(self):
"""setup test variables"""
self.app = create_app(config_name="testing")
self.client = self.app.test_client
self.category_data = {'name' : 'Yummy'}
# binds the app with the current context
with self.app.app_context():
#create all tables
db.session.close()
db.drop_all()
db.create_all()
def register_user(self, first_name='Tester', last_name='Api', username='apitester', email='[email protected]', password='abc'):
"""This helper method helps register a test user"""
user_data = {
'first_name' : first_name,
'last_name' : last_name,
'username' : username,
'email' : email,
'password' : password
}
return self.client().post('/api/v1.0/register', data=json.dumps(user_data), content_type='application/json')
def login_user(self, email='[email protected]', password='abc'):
"""this helper method helps log in a test user"""
user_data = {
'email' : email,
'password' : password
}
return self.client().post('/api/v1.0/login', data=json.dumps(user_data), content_type='application/json')
def test_category_creation(self):
"""Test that the Api can create a category"""
self.register_user()
login_result = self.login_user()
token = json.loads(login_result.data)
token = token['access_token']
# Create a category by going to that link
response = self.client().post('/api/v1.0/category', headers=dict(Authorization="Bearer " + token), data=json.dumps(self.category_data), content_type='application/json')
self.assertEquals(response.status_code, 201)
の可能性のある重複[フラスコユニットテスト:ログインユーザからの要求をテストする方法(https://stackoverflow.com/questions/16238462/flask-unit-test-how-ユーザからのテストリクエストを要求する) –
私は自分のユーザを識別するためにセッションを使用していません、flask_login拡張で提供されるcurre_user変数を使用しています。 – Harith