'How to configure pytest in FastAPI?
I'm trying to write some tests for my FastAPI -application. I have defined app
in main.py
like this: app = FastAPI()
. I try to import this in my test test_api.py
:
from fastapi.testclient import TestClient
from main import app
client = TestClient(app)
def test_read_main():
# test code
When I run the tests I get these errors:
E pydantic.error_wrappers.ValidationError: 4 validation errors for Settings
E SERVER_NAME
E field required (type=value_error.missing)
E SERVER_HOST
E field required (type=value_error.missing)
E PROJECT_NAME
E field required (type=value_error.missing)
E DATABASE_URL
E field required (type=value_error.missing)
How should I configure the tests so I could run them successfully?
Edit. This is the structure of the app.
project
│ .env
│
│
└───app
│
│
|───app
| │ main.py
| │
| |___config
| config.py
|
|
|───tests
test_file01.py
Solution 1:[1]
You need to define the environment vars in test,
import os
from fastapi.testclient import TestClient
os.environ['SERVER_NAME'] = 'server_name'
os.environ['SERVER_HOST'] = 'server_host'
os.environ['PROJECT_NAME'] = 'project_name'
os.environ['DATABASE_URL'] = 'DATABASE_URL'
from main import app
client = TestClient(app)
def test_read_main():
# test code
The app import needs to be after the env var definition, it's better to set your application as fixture.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Amine Bk |