-
Notifications
You must be signed in to change notification settings - Fork 98
Tests
Tests are a very important part of software development. Untested applications make it hard to improve existing code and creating new features without knowing whether you've regressed or not. Note that there should be integration tests if there are multiple services to your application. For the official documentation on Flask testing, look here. In addition, here's a good document on testing in python.
I've provided unit tests in the tests/
folder, which uses pytest to execute tests. The test example's use sqlite as a temporary database instead of postgres since these tests should be Idempotent and independent of it's environment, well besides the application and it's dependencies. This means that with the same code and same versions of dependencies, it should produce the same result. So, you can't have a persisting postgres database that you use in your tests because if you added a row to a Table, the tests may return a different result. You could setup a dockerized postgres image and run it every time when you test, but that'd be for integration tests. For unit tests, I'd argue that you don't need to do that. Instead of stubbing SQLAlchemy, which is very cumbersome and difficult in my opinion, I decided to use a sqlite database as a temporary database that SQLAlchemy would connect to. Sqlite is a just a file in which I remove once the tests are over. sqlite is much faster and easier to manage, especially if you want to use a dockerized continuous integration setup. So, when you run your tests, it will create that file and create the necessary database schema (look into tests/conftest.py
) and then your application will run very similar to your development environment. With testing, you want to figure out whether the code you wrote works, and generally when errors occur, it's probably not some complex database incompatibility issue, it's probably something that you wrote incorrectly. However, if you're planning your site to be really complex, I wouldn't use this method because sqlite and postgres are different in many ways. But if your app has simple queries, especially if your just using SQLAlchemy, unit testing with sqlite would work perfectly.
To run the tests, do:
$ pipenv run pytest tests
or do pipenv shell
and blah blah blah