如何从 docker-compose 中的 docker 容器运行 pytest

tob*_*ias 8 python postgresql pytest docker docker-compose

我想通过 pytest(test如下)从一个容器进行测试,另一个容器(web如下)是否与我们的 Postgresql DB 良好交互。

我有以下 docker-compose.yaml 文件

version: '3.8'

services:
  web:
    build: 
      context: ./src/
      dockerfile: Dockerfile
    command: |
      bash -c 'while !</dev/tcp/db/5432; do sleep 1; done; uvicorn app.main:app --reload --workers 1 --host 0.0.0.0 --port 8000'
    volumes:
      - ./src/:/usr/src/app/
    ports:
      - 8002:8000
    environment:
      - DATABASE_URL=postgresql://postgres:postgres@db:5432/postgres_dev
    depends_on:
      - db
  test:
    build: 
      context: ./src/
      dockerfile: Dockerfile-test
    volumes:
      - ./src/:/usr/src/app/
    stdin_open: true
    environment:
      - DATABASE_URL=postgresql://postgres:postgres@db:5432/postgres_dev
      - TEST_PORT=8002
    depends_on:
      - web
  db:
    image: postgres:13-alpine
    volumes:
      - postgres_data:/var/lib/postgresql/data/
    ports:
      - 5432:5432
    environment:
      - POSTGRES_USER=postgres
      - POSTGRES_PASSWORD=postgres
      - POSTGRES_DB=postgres_dev
volumes:
  postgres_data:
Run Code Online (Sandbox Code Playgroud)

此外,Dockerfile-test看起来像

# pull official base image
FROM python:3.9.4-alpine

# set work directory
WORKDIR /usr/src/

# set environment variables
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1

# copy requirements file
COPY ./tests/requirements.txt /usr/src/app/requirements.txt

# install dependencies
RUN set -eux \
    && apk add --no-cache --virtual .build-deps build-base \
        libressl-dev libffi-dev gcc musl-dev python3-dev \
        postgresql-dev bash \
    && pip install --upgrade pip setuptools wheel \
    && pip install -r /usr/src/app/requirements.txt \
    && rm -rf /root/.cache/pip

# copy project
COPY ./tests/ /usr/src/app/tests
Run Code Online (Sandbox Code Playgroud)

看起来requirements.txt

pytest==6.2.5
requests==2.26.0
pytest-httpserver==1.0.3
psycopg2==2.9.2
Run Code Online (Sandbox Code Playgroud)

和conftest.py看起来像

import pytest
import psycopg2

@pytest.fixture(scope='function')
def session():
    conn = psycopg2.connect(host="localhost", database="hello_fastapi_dev", user="hello_fastapi", password="hello_fastapi")
    # Create a cursor object
    session = conn.cursor()
    yield session
    # Close the cursor and connection to so the server can allocate
    # bandwidth to other requests
    session.close()
    conn.close()
Run Code Online (Sandbox Code Playgroud)

然而,当我跑步时

docker-compose up -d --build
docker-compose run test pytest
Run Code Online (Sandbox Code Playgroud)

我明白了

../local/lib/python3.9/site-packages/requests/adapters.py:516: ConnectionError
=========================================================================================================================== short test summary info ============================================================================================================================
FAILED app/tests/test_projects.py::test_ping - requests.exceptions.ConnectionError: HTTPConnectionPool(host='localhost', port=8002): Max retries exceeded with url: /ping (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7faf175a86a0>: Failed...
FAILED app/tests/test_projects.py::test_auth - requests.exceptions.ConnectionError: HTTPConnectionPool(host='localhost', port=8002): Max retries exceeded with url: /auth/register (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7faf174d0070...
ERROR app/tests/test_projects.py::test_project_create - psycopg2.OperationalError: could not connect to server: Connection refused
========================================================================================================================== 2 failed, 1 error in 0.49s ==========================================================================================================================
ERROR: 1
Run Code Online (Sandbox Code Playgroud)

因此,我似乎无法建立连接。你能帮我一下吗?