I am trying to test my log in functionality with Flask-Testing. I'm following the Flask docs on testing as well. The test_login() function raises AttributeError: 'Flask' object has no attribute 'post'. Why am I getting this error?
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
It looks like Flask-Testing magically sets up a special app client object on the TestCase instance named self.client. Change all self.app to self.client and it should fix that issue.
Eg:
def login(self, username, password):
return self.app.post('/login', data=dict(
username=username,
password=password
), follow_redirects=True)
to:
def login(self, username, password):
return self.client.post('/login', data=dict(
username=username,
password=password
), follow_redirects=True)
While writing tests for my Flask app I came across a similar problem.
Only from debugging I saw that there was no "config" attribute instead I had to go self.app.application.config
Not sure why it's missing, I've usually always done self.app.config just like in the production code
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With