如何在flask应用程序中测试登录(使用MySQL)?

我在
this tutorial之后一直在学习烧瓶.现在我正在尝试使用python unittest测试应用程序的某些部分.但我无法掌握如何测试用户登录.这是我正在尝试的测试代码:

from intro_to_flask import app
from models import db
from models import User

class BaseTestCase(unittest.TestCase):

def setUp(self):
    app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://credentials/database'
    app.config['TESTING'] = True
    app.config['CSRF_ENABLED'] = False
    with app.app_context():
        db.create_all()


def tearDown(self):
    with app.app_context():
        db.session.remove()
        db.drop_all()

def test_User_login(self):
    tester = app.test_client(self)
    u = User(firstname = 'testname', lastname = 'testlaname', email = 'test@example.com', password = 'pass')
    with app.app_context():
        db.session.add(u)
        db.session.commit()
    response = tester.post('/signin', data=dict(email = 'test@example.com', password = 'pass'), follow_redirects=True )
    self.assertIn(b'Profile', response.data) #User is redirected to profile page after loggin in which has giant Profile

if __name__ == '__main__':
    unittest.main()

测试失败并且很明显,登录和以下重定向不会发生.

我在测试中添加了以下print语句:

打印(响应)
打印(response.data)

其中产生了以下结果:

打印(响应)

<Response streamed [200 OK]>

打印(response.data)

<!DOCTYPE html>
<html>
  <head>
    <title>Flask App</title>
    <link rel="stylesheet" href="/static/css/main.css">
  </head>
  <body>

  <header>
    <div class="container">
      <h1 class="logo">Image Hosting Test v 0.2</h1>
      <nav>
        <ul class="menu">
          <li><a href="/">Home</a></li>
          <li><a href="/about">About</a></li>
          <li><a href="/contact">Contact</a></li>

          <li><a href="/signup">Sign Up</a></li>
          <li><a href="/signin">Sign In</a></li>

        </ul>
      </nav>
    </div>
  </header>

    <div class="container">

  <h2>Sign In</h2>





  <form action="/signin" method=post>
    <div style="display:none;"><input id="csrf_token" name="csrf_token" type="hidden" value="1463805648##fcc7e953937a80b6744554aed86d092fcf70e1fb"></div>

    <label for="email">Email</label>
    <input id="email" name="email" type="text" value="test@example.com">

    <label for="password">Password</label>
    <input id="password" name="password" type="password" value="">

    <input id="submit" name="submit" type="submit" value="Sign In">
  </form>


    </div>

  </body>
</html>

有人可以向我解释一下,我的测试有什么问题吗?

Python版本:2.7.9
MySQL版本:5.7
Flask版本:0.10.1
操作系统Windows 10

最佳答案 啊,我认为这是导致它的CSRF保护.尝试通过设置禁用它

app.config['WTF_CSRF_ENABLED'] = False
点赞