title: Flask unittest and sqlalchemy using all connections
body: <p>I've just run into an issue running unittests on my flask app after I had roughly 100 unittests. All unittests will pass, but when run all at once they will fail with the following error:</p>
  
  <pre><code>OperationalError: (OperationalError) FATAL:  remaining connection slots are reserved for non-replication superuser connections
  </code></pre>
  
  <p>Everything is running in a virtualbox/vagrant/ubuntu12.04 instance on local machine. My postgres max_connections is set to 100 so I'm assuming that the connections aren't closing and after running 100 tests I use up all the available ones. </p>
  
  <p>This person <a href="https://stackoverflow.com/questions/16117094/flask-unit-tests-with-sqlalchemy-and-postgresql-exhausts-db-connections">Flask unit tests with SQLAlchemy and PostgreSQL exhausts db connections</a> looks like they are having the same exact problem. Mike/Zzzeek (sqlalchemy dev) even responded to it saying that something may be happening in create_app() so I've included that as well below. </p>
  
  <p>Does this mean I'm not closing my connections somewhere? All of these errors are triggered by <code>db.create_all()</code> in my setUp() method of my unittest. </p>
  
  <p># test.py</p>
  
  <pre><code>class TestCase(DataMixin, Base):
      """Base test class"""
  
      def create_app(self):
          return create_app(TestConfig())
  
      def setUp(self):
          db.create_all()
  
      def tearDown(self):
          db.session.remove()
          db.drop_all()
  </code></pre>
  
  <p># app.py</p>
  
  <pre><code>def create_app(config=None):
      app = Flask(__name__)
  
      # Config
      app.config.from_object(BaseConfig())
      if config is not None:
          app.config.from_object(config)
  
      # Extensions
      db.init_app(app)
      mail.init_app(app)
      bcrypt.init_app(app)
  
      # Blueprints
      app.register_blueprint(core_blueprint, url_prefix='/')
      app.register_blueprint(accounts_blueprint, url_prefix='/account')
      app.register_blueprint(admin_blueprint, url_prefix='/admin')
      app.register_blueprint(cart_blueprint, url_prefix='/cart')
  
      # Login Manager
      login_manager.setup_app(app, add_context_processor=True)
      login_manager.login_view = "accounts.login"
      login_manager.user_callback = load_user
  
      # Templates
      app.jinja_env.globals['is_admin'] = is_admin
      app.jinja_env.globals['is_staff'] = is_staff
  
      @app.context_processor
      def inject_cart():
          cart = count = None
          if current_user.is_authenticated():
              cart = current_user.get_cart()
          return dict(cart=cart)
  
      # Error Handling
      @app.errorhandler(404)
      def page_not_found(error):
          return render_template('404.html'), 404
  
      return app
  </code></pre>