[Flask] Flask-sqlalchemy and testing
gabor at szabgab.com
Thu May 13 09:57:00 EDT 2021
Nicolas, thanks. That helped a lot and I managed to write a full example
that shows this: https://code-maven.com/flask-counter-sqlite-sqlalchemy
However I still have an issue. We use yoyo to manage migrations and I
wanted to try the automap feature of SQLAlchemy. I could not solve it
elegantly just this way:
* There is a "global" in the model.py
* I could not figure out how to create the classes for the table(s) so I
added them to a "base" class.
* I had to change the query code from Counter.query.all()
Any suggestions there?
On Wed, May 12, 2021 at 12:12 PM Nicolas Le Manchet <nicolas at lemanchet.fr>
> You should take a look at application factories (
> https://flask.palletsprojects.com/en/1.1.x/patterns/appfactories/). It's
> a pattern that allows to have multiple applications configured differently
> in the same interpreter, which tends to make testing easier.
> On Wed, May 12, 2021, at 11:00, Gabor Szabo wrote:
> > Hi,
> > I am working on an application using Flask-sqlalchemy and I am not sure
> > how to write tests properly.
> > In all the examples I have seen so far the main flask file has the line
> > db = SQLAlcehmy(app)
> > meaning this is executed when the main file of Flask is loaded. so if
> > the test file has
> > import app
> > that would still happen at compile time. This way I have only one
> > chance to set up a test-database , right before that import-statement.
> > In order to make it easier to use different test database we moved the
> > db = SQLAlcehmy(app)
> > call inside a function decorated with before_first_request.
> > This ensures the code is called for regular use and we can call the
> > before_first_request method for each test. Because we don't have db at
> > load time we also had to move all the class-declarations in this
> > function (because they all inherit from db.Model).
> > The problem is that now all the model classes are scoped to this
> > function. We had to use "global" to make them accessible to the rest of
> > the code.
> > That does not look right.
> > The code can be found here: https://github.com/rnewstead1/workout-app/
> > (together with the tests)
> > And you can actually see our struggle in this video:
> > https://code-maven.com/workout-app-2
> > I'd appreciate your insight on how to make this nicer or even just a
> > link to a code-base that has such tests.
> > Gabor
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Flask