Suppose I'm following the Flask-SQLAlchemy quickstart example, and I want to add a couple of unittests.
My model might look something like:
db = SQLAlchemy(app)
Base = db.Model
class Account(Base):
id = Column(Integer, primary_key=True)
name = Column(String(1000))
For unittesting, I'll want to create and destroy a database for each test.
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(...)
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.
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 app.config['SQLALCHEMY_DATABASE_URI'] to point to a database.
What's the right way to create test databases and point a test thread to them with Flask-SQLAlchemy?