To finish this group of chapters about **FastAPI** with **SQLModel**, let's now learn how to implement automated tests for an application using FastAPI with SQLModel. ✅
Including the tips and tricks. 🎁
## FastAPI Application
Let's work with one of the **simpler** FastAPI applications we built in the previous chapters.
All the same **concepts**, **tips** and **tricks** will apply to more complex applications as well.
We will use the application with the hero models, but without team models, and we will use the dependency to get a **session**.
Now we will see how useful it is to have this session dependency. ✨
Now we will have a Python project with multiple files, one file `main.py` with all the application, and one file `test_main.py` with the tests, with the same ideas from [Code Structure and Multiple Files](../code-structure.md){.internal-link target=_blank}.
The file structure is:
```
.
├── project
├── __init__.py
├── main.py
└── test_main.py
```
## Testing FastAPI Applications
If you haven't done testing in FastAPI applications, first check the <ahref="https://fastapi.tiangolo.com/tutorial/testing/"class="external-link"target="_blank">FastAPI docs about Testing</a>.
Then, we can continue here, the first step is to install the dependencies, `requests` and `pytest`.
Make sure you do it in the same [Python environment](../index.md#create-a-python-virtual-environment){.internal-link target=_blank}.
<divclass="termy">
```console
$ python -m pip install requests pytest
---> 100%
```
</div>
## Basic Tests Code
Let's start with a simple test, with just the basic test code we need the check that the **FastAPI** application is creating a new hero correctly.
If we run it, it will use the same **production database** that we are using to store our very important **heroes**, and we will end up adding unnecesary data to it, or even worse, in future tests we could end up removing production data.
So, we should use an independent **testing database**, just for the tests.
To do this, we need to change the URL used for the database.
But when the code for the API is executed, it gets a **session** that is already connected to an **engine**, and the **engine** is already using a specific database URL.
Even if we import the variable from the `main` module and change its value just for the tests, by that point the **engine** is already created with the original value.
But all our API *path operations* get the *session* using a FastAPI **dependency**, and we can override dependencies in tests.
Here's where dependencies start to help a lot.
## Override a Dependency
Let's override the `get_session()` dependency for the tests.
This dependency is used by all the *path operations* to get the **SQLModel** session object.
We will override it to use a different **session** object just for the tests.
That way we protect the production database and we have better control of the data we are testing.
Here we create all the tables in the testing database with:
```Python
SQLModel.metadata.create_all(engine)
```
But remember that [Order Matters](../create-db-and-table.md#sqlmodel-metadata-order-matters){.internal-link target=_blank} and we need to make sure all the **SQLModel** models are already defined and **imported** before calling `.create_all()`.
In this case, it all works for a little subtlety that deserves some attention.
Because we import something, *anything*, from `.main`, the code in `.main` will be executed, including the definition of the **table models**, and that will automatically register them in `SQLModel.metadata`.
That way, when we call `.create_all()` all the **table models** are correctly registered in `SQLModel.metadata` and it will all work. 👌
But SQLite also supports having an **in memory** database. This means that all the database is only in memory, and it is never saved in a file on disk.
After the program terminates, **the in-memory database is deleted**, so it wouldn't help much for a production database.
But **it works great for testing**, because it can be quickly created before each test, and quickly removed after each test. ✅
And also, because it never has to write anything to a file and it's all just in memory, it will be even faster than normally. 🏎
<details>
<summary>
Other alternatives and ideas 👀
</summary>
Before arriving at the idea of using an **in-memory database** we could have explored other alternatives and ideas.
The first is that we are not deleting the file after we finish the test, so the next test could have **leftover data**. So, the right thing would be to delete the file right after finishing the test. 🔥
But if each test has to create a new file and then delete it afterwards, running all the tests could be **a bit slow**.
Right now, we have a file `testing.db` that is used by all the tests (we only have one test now, but we will have more).
So, if we tried to run the tests at the same time **in parallel** to try to speed things up a bit, they would clash trying to use the *same*`testing.db` file.
Of course, we could also fix that, using some **random name** for each testing database file... but in the case of SQLite, we have an even better alternative by just using an **in-memory database**. ✨
Do we really have to duplicate all that for **each test**? No, we can do better! 😎
We are using **pytest** to run the tests. And pytest also has a very similar concept to the **dependencies in FastAPI**.
!!! info
In fact, pytest was one of the things that inspired the design of the dependencies in FastAPI.
It's a way for us to declare some **code that should be run before** each test and **provide a value** for the test function (that's pretty much the same as FastAPI dependencies).
In fact, it also has the same trick of allowing to use `yield` instead of `return` to provide the value, and then **pytest** makes sure that the code after `yield` is executed *after* the function with the test is done.
In pytest, these things are called **fixtures** instead of *dependencies*.
Let's use these **fixtures** to improve our code and reduce de duplicated boilerplate for the next tests.
## Pytest Fixtures
You can read more about them in the <ahref="https://docs.pytest.org/en/6.2.x/fixture.html"class="external-link"target="_blank">pytest docs for fixtures</a>, but I'll give you a short example for what we need here.
* To use a pytest fixture in a function, we have to declare the parameter with the **exact same name**. In FastAPI we have to **explicitly use `Depends()`** with the actual function inside it.
But apart from the way we declare them and how we tell the framework that we want to have them in the function, they **work in a very similar way**.
**pytest** will make sure to run them right before (and finish them right after) each test function. So, each test function will actually have its own database, engine, and session.
## Client Fixture
Awesome, that fixture helps us prevent a lot of duplicated code.
But normally we will create **lots of other test functions**. And now all the boilerplate and complexity is **written only once**, in those two fixtures.
Now, any additional test functions can be as **simple** as the first one, they just have to **declare the `client` parameter** to get the `TestClient`**fixture** with all the database stuff setup. Nice! 😎
Using the same ideas, requiring the fixtures, creating data that we need for the tests, etc., we can now add the rest of the tests. They look quite similar to what we have done up to now.
And tests will be notoriously useful when **refactoring** your code, **changing things**, **adding features**. Because tests can help catch a lot of errors that can be easily introduced by refactoring.
And they will give you the confidence to work faster and **more efficiently**, because you know that you are checking if you are **not breaking anything**. 😅
I think tests are one of those things that bring your code and you as a developer to the next professional level. 😎
And if you read and studied all this, you already know a lot of the advanced ideas and tricks that took me years to learn. 🚀