[Flask] Flask-sqlalchemy and testing

Gabor Szabo gabor at szabgab.com
Wed May 12 05:00:24 EDT 2021


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...
URL: <https://mail.python.org/pipermail/flask/attachments/20210512/1df4afee/attachment.html>


More information about the Flask mailing list