Commits

Anonymous committed 6f6da35

sqlalchemy gotcha

Comments (0)

Files changed (1)

 session is properly removed and that a new session is started with each test run - this is a common
 "gotcha".
 
+Another gotcha is that Flask-SQLAlchemy **also** removes the session instance at the end of every request (as
+should any threadsafe 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. 
+
+For example::
+
+    class SomeTest(MyTest):
+        
+        def test_something(self):
+
+            user = User()
+            db.session.add(user)
+            db.session.commit()
+
+            # this works
+            assert user in db.session
+
+            response = self.client.get("/")
+
+            # this raises an AssertionError
+            assert user in db.session
+
+You now have to re-add the "user" instance back to the session with ``db.session.add(user)``, if you are going
+to make any further database operations on it.
+
 Also notice that for this example the SQLite in-memory database is used : while it is faster for tests,
 if you have database-specific code (e.g. for MySQL or PostgreSQL) it may not be applicable.
 
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.