我在我的烧瓶应用中使用 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='tester@api.com', 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='tester@api.com', 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)
答案 0 :(得分:3)
您需要使用与登录时相同的上下文。这就是您需要在代码中添加的内容:
with self.client() as c:
然后使用c
制作获取,发布或任何其他您想要的请求。这是一个完整的例子:
import unittest
from app import create_app
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'}
def test_category_creation(self):
"""Test that the user can create a category"""
with self.client() as c:
# use the c to make get, post or any other requests
login_response = c.post("""login the user""")
# Create a category by going to that link using the same context i.e c
response = c.post('/api/v1.0/category', self.category_data)