[Flask] Flask-sqlalchemy and testing

Nicolas Le Manchet nicolas at lemanchet.fr
Wed May 12 05:11:24 EDT 2021


Hi,

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
> 
> 
> _______________________________________________
> Flask mailing list
> Flask at python.org <mailto:Flask%40python.org>
> https://mail.python.org/mailman/listinfo/flask
> 


-- 
Nicolas Le Manchet


More information about the Flask mailing list