I have a Flask application setup with Flask-SQLAlchemy, and I'm running the tests with factory-boy. I'm trying to wrap the tests within transactions, so as not to fill up the db with test data (and avoid having to drop/recreate the db between tests, since it's pretty expensive).
However, since the db session is removed after each request, the objects created for the test are lost unless I commit the session before making the request.
Is there a way of sharing the session between the test context and the request context?
Here's a test example:
class TestUserViews(unittest.TestCase):
def setUp(self):
self.client = app.test_client()
def test_user_detail(self):
with app.test_request_context():
# Make sure requesting an unknown user returns a 404
response = self.client.get('/users/123/')
assert response.status_code == 404
# Create a user
user = UserFactory()
db.session.commit()
response = self.client.get('/users/{}/'.format(user.id))
assert response.status_code == 200 # This works since the write was committed
def test_user_uncommitted(self):
with app.test_request_context():
# Create a user
uncommitted_user = UserFactory()
assert uncommitted_user in db.session
response = self.client.get('/users/{}/'.format(uncommitted_user.id))
assert response.status_code == 200 # This doesn't work, the session wasn't reused
I built a dummy project on github to show a more complete example if necessary. Any idea what I'm missing here? Thanks!