Sqlalchemy Session Not Deleted Properly in Flask Tests

I am using Flask-Testing which says:

Another problem is that Flask-SQLAlchemy also deletes the session instance at the end of each query (like any thread-safe application using SQLAlchemy with scoped_session). Therefore, the session is cleared along with any objects added to it every time you call client.get () or another client method.

However, I do not see this. This test fails:

from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.testing import TestCase

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'
db = SQLAlchemy(app)
@app.route('/')
def index():
  print 'before request:', `db.session`
  u = db.session.query(User).first()
  u.name = 'bob'
  return ''

class User(db.Model):
  id = db.Column(db.Integer, primary_key=True)
  name = db.Column(db.String)

class SessionTest(TestCase):

  def create_app(self):
    return app

  def test_remove(self):
    db.drop_all()
    db.create_all()

    u = User()
    u.name = 'joe'
    db.session.add(u)
    db.session.commit()
    client = app.test_client()
    client.get('/')
    print 'after request:', `db.session`
    print u.name
    assert u not in db.session

(Run with $ nosetests test_file.pyto see it in action.)

standard output:

-------------------- >> begin captured stdout << ---------------------
before request: <sqlalchemy.orm.scoping.ScopedSession object at 0x10224c610>
after request: <sqlalchemy.orm.scoping.ScopedSession object at 0x10224c610>
bob

--------------------- >> end captured stdout << ----------------------

According to the documents, the user ushould not be in the session after the request for receipt, but it is! Does anyone know why this is happening?

, u.name - bob, joe, ! ( , .)

$ pip freeze | grep Flask
Flask==0.10.1
Flask-Bcrypt==0.5.2
Flask-DebugToolbar==0.8.0
Flask-Failsafe==0.1
Flask-SQLAlchemy==0.16
Flask-Script==0.6.2
Flask-Testing==0.4
Flask-Uploads==0.1.3
Flask-WTF==0.8
+4
3

, - , SQLAlchemy , , .

, - , , .

, , , , , '/', .

. .

Flask-SQLAlchemy app.teardown_appcontext, db.session.remove().

, / . - .

, , before_request after_request, client.get().

:

def test_remove(self):
  db.drop_all()
  db.create_all()

  u = User()
  u.name = 'joe'
  db.session.add(u)
  db.session.commit()
  with app.app_context():
      client = app.test_client()
      client.get('/')
  print 'after request:', `db.session`
  print u.name
  assert u not in db.session

.

Flask-Testing , , . , - , - , Flask Flask-SQLAlchemy.

, !

+8

FlaskClient , -SQLAlchemy shutdown_session app.teardown_appcontext Flask 0.9. , bacause flask.ext.testing.TestCase setUp tearDown.

0

, Flask-Manage . .

import threading
# some code omited
runner = unittest.TextTestRunner(verbosity=2)
t = threading.Thread(target=runner.run, args=[test_suite])
t.start()
t.join()
# other code omited
0

All Articles