2016-01-21 71 views
2

我想用Flask-Testing测试我的日志功能。我也遵循Flask docs on testingtest_login()函数引发AttributeError: 'Flask' object has no attribute 'post'。为什么我得到这个错误?'烧瓶'对象没有属性'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="[email protected]") 
    user2 = User(username="lucas", email="[email protected]") 

    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 

回答

2

它看起来像Flask-Testing奇迹般地建立了名为self.client TestCase的实例的特殊应用程序客户端对象。将所有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) 
+0

由于@jumbopap但是我现在有断言错误:'( 时引发的错误我的路线定义如下: @ app.route(“/ login”,methods = [“GET”,“POST”)我的路线定义如下: @ app.route ]) def login(): 任何想法可能是什么错? :) –

+2

您的实际生产应用程序未由此测试套件进行测试。您在'create_app'中创建了一个完全独立的应用程序,该应用程序没有'/ login'路径。您需要从存储的任何位置导入生产应用程序,并将其返回到'create_app'方法中。 – jumbopap

相关问题