Automating database creation for testing
With some modification to manual_set_up
and test_dbs
I was able to run code.
For mysql database, I remove database name from the db_url
. And db.drop_all()
also fails because the database does not exist so I put in try/except and pass the exception here. Then before db.create_all()
I create a sqlachemy engine bypassing db_url
which does not have database name db.create_engine(db_url)
.
# your imports ...
import sqlalchemy.exc
#...
TEST_DATABASE_URL_MYSQL = 'mysql+pymysql://root:@127.0.0.1:3306/'
def manual_set_up(self, db_url, db_kind, db_name=None):
if db_kind == "mysql":
self.app = create_app(db_url + db_name)
else:
self.app = create_app(db_url)
self.app_context = self.app.app_context()
self.app_context.push()
try:
db.drop_all()
except sqlalchemy.exc.InternalError as e:
if "unknown database" in str(e.args[0]).lower():
pass
try:
db.create_all()
except sqlalchemy.exc.InternalError as e:
if "unknown database" in str(e.args[0]).lower():
db.create_engine(db_url, {}).execute(f"CREATE DATABASE IF NOT EXISTS {db_name};")
db.create_all()
def test_dbs(self):
for args in [(TEST_DATABASE_URL_MEMORY, "sqlite"),
(TEST_DATABASE_URL_MYSQL, "mysql", "somewords")]:
self.manual_set_up(*args)
self.insert()