简体   繁体   English

Python Flask单元测试中的登录测试失败

[英]login test failing in Python Flask unit test

I am trying to test the login functionality for my Python Flask app. 我正在尝试测试我的Python Flask应用程序的登录功能。

I create a user and add them to the database in the test_adduser() test and that passed fine. 我创建了一个用户,并在test_adduser()测试中将它们添加到数据库中,并且一切顺利。 However, the test_login() test fails with an assertion error. 但是, test_login()测试失败,并带有断言错误。 I have debugged the code and the test loads the login page ok (so I know the problem is not with the app or the routes etc) but it does not log in and redirect the user. 我已经调试了代码,并且测试成功加载了登录页面(因此我知道问题不在于应用程序或路由等),但它无法登录并重定向用户。

I realise that this post is a bit short on description ie the error trace, however the error is literally "AssertionError". 我意识到这篇文章的描述有点短,即错误跟踪,但是错误实际上是“ AssertionError”。
Maybe I am doing something obviously wrong, like the way I am passing in the user credentials to the test and someone could point this out to me? 也许我做错了明显的事情,例如我将用户凭据传递给测试的方式,有人可以向我指出这一点吗?

Thanks! 谢谢!

from flask.ext.testing import TestCase
from flask import Flask
from Shares import db, app as appy
from Shares.models import User
import manage


class test(TestCase):

def create_app(self):
    app = Flask(__name__)
    app.config['TESTING'] = True
    return appy

SQLALCHEMY_DATABASE_URI = "sqlite://"
TESTING = True

def setUp(self):

    manage.initdb()
    #print self.login('lucas', 'test').data

def tearDown(self):

    db.session.remove()
    db.drop_all()

def login(self, username, password):
    return self.client.post('/login', data=dict(
        username=username,
        password=password
    ), follow_redirects=True)

def logout(self):
    return self.client.get('/logout', follow_redirects=True)

def test_adduser(self):

    lucas=User(username="lucas", email="lucas@example.com", password="test")
    user2 = User(username="lucas", email="lucas@test.com")

    db.session.add(lucas)
    db.session.commit()

    assert lucas in db.session
    assert user2 not in db.session

def test_login(self):
    lucas=User(username="lucas", email="lucas@example.com", password="test")
    db.session.add(lucas)

    rv = self.login('lucas', 'test')
    assert 'Welcome' in rv.data

Ok so I worked it out in the end. 好的,我最终解决了。 I needed to deactivate the CSRF protection. 我需要停用CSRF保护。 This did the trick: 这达到了目的:

def create_app(self):
    app = Flask(__name__)
    appy.config['TESTING'] = True
    appy.config['WTF_CSRF_ENABLED'] = False
    return appy

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM