我正在尝试使用烧瓶测试我的登录功能。 我也在关注 Flask 文档进行测试。test_login()
函数会引发AttributeError: 'Flask' object has no attribute 'post'
。 为什么我会收到此错误?
Traceback (most recent call last):
File "/home/lucas/PycharmProjects/FYP/Shares/tutorial/steps/test.py", line 57, in test_login_logout
rv = self.login('lucas', 'test') <br> <br>
File "/home/lucas/PycharmProjects/FYP/Shares/tutorial/steps/test.py", line 47, in login
return self.app.post('/login', data=dict(
AttributeError: 'Flask' object has no attribute 'post'
from flask.ext.testing import TestCase
from flask import Flask
from Shares import db
import manage
class test(TestCase):
def create_app(self):
app = Flask(__name__)
app.config['TESTING'] = True
return app
SQLALCHEMY_DATABASE_URI = "sqlite://"
TESTING = True
def setUp(self):
manage.initdb()
def tearDown(self):
db.session.remove()
db.drop_all()
def test_adduser(self):
user = User(username="test", email="test@test.com")
user2 = User(username="lucas", email="lucas@test.com")
db.session.add(user)
db.session.commit()
assert user in db.session
assert user2 not in db.session
def login(self, username, password):
return self.app.post('/login', data=dict(
username=username,
password=password
), follow_redirects=True)
def logout(self):
return self.app.get('/logout', follow_redirects=True)
def test_login(self):
rv = self.login('lucas', 'test')
assert 'You were logged in' in rv.data
看起来 Flask-Testing 神奇地在 TestCase 实例上设置了一个名为 self.client
的特殊应用程序客户端对象。将所有self.app
更改为self.client
,它应该可以解决此问题。
例如:
def login(self, username, password):
return self.app.post('/login', data=dict(
username=username,
password=password
), follow_redirects=True)
自:
def login(self, username, password):
return self.client.post('/login', data=dict(
username=username,
password=password
), follow_redirects=True)
在为我的 Flask 应用程序编写测试时,我遇到了类似的问题。
只是从调试中我看到没有"配置"属性,而是我不得不去self.app.application.config
不知道为什么它丢失了,我通常总是像在生产代码中一样做self.app.config
import unittest
from factory import create_app
class ConfigTests(unittest.TestCase):
def setUp(self):
app = create_app('flask_test.cfg')
app.testing = True
self.app = app.test_client()
def test_app_is_development(self):
self.assertFalse(self.app.application.config['SECRET_KEY'] is 'secret_key')
self.assertTrue(self.app.application.config['DEBUG'] is True)