简体   繁体   中英

Implement pytest over FastAPI app running in Docker

I've created FasAPI app with Postgres DB which lives in docker container. So now I have docker-compose.yml file with my app and postgres DB:

version: '3.9'

services:
  app:
    container_name: app_container
    build: .
    volumes:
      - .:/code
    ports:
      - '8000:8000'
    depends_on:
      - my_database
    #networks:
    #  - postgres

  my_database:
    container_name: db_container
    image: postgres
    environment:
      POSTGRES_NAME: dbf
      POSTGRES_USER: myuser
      POSTGRES_PASSWORD: password
    volumes:
       - postgres:/data/postgres
    ports:
      - '5432:5432'
    restart: unless-stopped
volumes:
    postgres:

And now I want to make pytest over my DB with testing endpoints and testing my DB BUT, when I run python -m pytest cmd I got the error can not translate hostname "my_database" as in my database.py file I have to set DATABASE_URL = 'postgresql://myuser:password@my_database' . As according to userguide, when I build docker-compose file, in DATABASE_URL I must put name of service instead of hostname.

Anyone have an idea how to solve it?!!

The problem is that, if you use docker-compose to run your app in separate container and run database in another container. It is like your DB is not launched and pytest can't connect to it. This is wrong way to implement pytests in this way!!!!

To run pytest correctly you should:

  1. You must in DATABASE_URL write the name of service instead of the name of host! In my case my_database is name of service in docker-compose.yml file, so I should set it as hostname, like: DATABASE_ULR = postgres://<username>:<password>@<name of service>
  2. pytest must be run in app container! What it means! First of all, start your containers: docker-copose up --build where --build is optional (it just rebuilds your images if you made some changes to code in your programm files. After this, you should jump into app container . It can be done from Docker application on your computer or through the terminal. To make it with terinal window:
    • cmd: docker exec -it <name of container with your application> . You will dive into container and after this you can simply run cmd pytest or python -m pytest . And your tests will run as allways.

If you will have some questions you can write me anytime)))

So, the reason of this Error was that I run pytest and it tried to connect to DATABASE_URL which, em... has not been launched already (as I understand).

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