title: When unittesting with Flask, Flask-SQLAlchemy, and SQLAlchemy, how do I isolate test databases between threads?
body: <p>Suppose I'm following the <a href="http://flask-sqlalchemy.pocoo.org/2.1/quickstart/" rel="nofollow noreferrer">Flask-SQLAlchemy</a> quickstart example, and I want to add a couple of unittests.</p>
  
  <p>My model might look something like:</p>
  
  <pre><code>db = SQLAlchemy(app)
  Base = db.Model
  
  class Account(Base):
      id = Column(Integer, primary_key=True)
      name = Column(String(1000))
  </code></pre>
  
  <p>For unittesting, I'll want to create and destroy a database for each test.</p>
  
  <pre><code>def _setup_database():
      db_name = 'test_%s' % random.randint(0,999999)
  
      # (Code that creates database with db_name and setups the schema)
  
      app.config['DB_NAME'] = db_name
      app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql:///{}'.format(db_name)
  
  
  def _destroy_db():
      db_name = app.config['DB_NAME']
  
      # Code that destroys the test db
  
  
  class TestAccounts(unittest.TestCase):
      def setUp(self):
          _setup_database()
  
      def tearDown(self):
          _destroy_db()
  
      def test_new_signup(self):
          account = models.Account(...)
  
      def test_something_else(self):
          account = models.Account(...)
  </code></pre>
  
  <p>The problem here is that, if I run this code in an environment where unittests are multi-threaded, there is a race condition. Two databases are usually setup simultaneously and app.config is pointed to one of them.</p>
  
  <p>If I were using SQLAlchemy directly, I would create a new session for each test and use that session. But Flask-SQLAlchemy creates sessions for me, and as such, seems to depend on having one global <code>app.config['SQLALCHEMY_DATABASE_URI']</code> to point to a database.</p>
  
  <p>What's the right way to create test databases and point a test thread to them with Flask-SQLAlchemy?</p>