You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用psycopg[binary]运行pytest-postgresql时遇pg_config缺失错误

解决pytest-postgresql找不到pg_config的问题

问题根源

你遇到的ExecutableMissingException是因为psycopg[binary]只是PostgreSQL的客户端驱动,仅提供连接数据库的能力,不包含PostgreSQL服务器端的可执行文件(比如pg_config、postgres、pg_ctl这些)。而pytest-postgresql默认会尝试在本地启动一个临时PostgreSQL实例,必须依赖这些服务器端工具才能正常工作。

解决方案

方案1:在Docker镜像中安装PostgreSQL服务器

基于你使用的python:3.11-slim(Debian基础镜像),可以通过apt安装完整的PostgreSQL服务器包,让pytest-postgresql能找到所需的可执行文件。

修改后的Dockerfile:

FROM python:3.11-slim

# 安装PostgreSQL服务器及依赖,清理apt缓存减少镜像体积
RUN apt-get update && apt-get install -y --no-install-recommends postgresql && rm -rf /var/lib/apt/lists/*

# 创建PostgreSQL数据目录并设置权限
ENV PGDATA=/var/lib/postgresql/data
RUN mkdir -p $PGDATA && chown postgres:postgres $PGDATA

# 安装Python依赖
RUN pip install pytest==7.3.2 pytest-postgresql==5.0.0 psycopg[binary]==3.1.12

WORKDIR /tests
COPY test.py .

# PostgreSQL默认禁止root用户启动,切换到postgres用户运行测试
USER postgres
ENTRYPOINT [ "pytest", "test.py" ]

同时修正测试代码中的连接字符串(psycopg3不需要postgresql+psycopg2://前缀):

import pytest
import psycopg


@pytest.fixture(scope="function")
def db_session(postgresql):
    # 直接通过参数构造psycopg3的连接
    with psycopg.connect(
        dbname=postgresql.info.dbname,
        user=postgresql.info.user,
        host=postgresql.info.host,
        port=postgresql.info.port
    ) as conn:
        yield conn


def test_something(db_session):
    assert True

方案2:连接外部已有的PostgreSQL服务

如果不想在镜像中安装PostgreSQL,可以配置pytest-postgresql直接连接外部的数据库实例,无需启动本地临时服务。

  1. 添加pytest.ini配置文件:
[pytest]
postgresql-host = 你的PostgreSQL主机地址
postgresql-port = 5432
postgresql-user = 你的数据库用户名
postgresql-dbname = 你的数据库名
  1. 保持原Dockerfile不变(无需安装PostgreSQL),运行容器时确保能访问外部数据库(比如通过Docker网络连接)。

内容的提问来源于stack exchange,提问作者Henrique Melo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 19:04:50