2016-01-21 49 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

相關問題