miguelgrinberg / flasky

Companion code to my O'Reilly book "Flask Web Development", second edition.
MIT License
8.54k stars 4.21k forks source link

A 'SQLAlchemy' instance has already been registered on this Flask app. Import and use that instance instead. #557

Open Patrickcob opened 1 year ago

Patrickcob commented 1 year ago

If was curious about the way you made the unit tests in flask. I have a similar project with a very close architecture. I have a much more recent version of flask, flask-sqlalchemy and etc. I was curious if anyone was having problem with this project related to unit testing.

While creating an instance of the app in the test, it raise an error that RuntimeError: A 'SQLAlchemy' instance has already been registered on this Flask app. Import and use that instance instead.

From my understanding, when usingflask test --coverage, it will create an instance of the app, than run the tests that try to create their own instances of the app. but in the create_app function, it tries to init the db with db.init_app(app) and it seems that, without surprise, there is a runtime error raised, because the database used is already in used, in this case, its a in-memory db. Something wrong or is this part of the newer flask and incompatible with this project?

miguelgrinberg commented 1 year ago

The problem is that you are trying to attach two Flask-SQLAlchemy extensions to the same Flask app instance. This suggests you are not creating a brand new app for each test, as is done in the tests in this project.