简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM