在 Python 单元测试中连接到本地 dockerized Perforce 服务器

Connecting to local dockerized Perforce server in Python unittests

我维护着一个 Python 工具,它 运行 可以针对 Perforce 服务器实现自动化。出于显而易见的原因,我的部分测试套件(使用 Pytest 的 unittest.TestCase 类 运行)需要一个实时服务器。到目前为止,我一直在使用远程测试服务器,但我想将其移动到我的本地环境中,并将服务器初始化作为我的预测试设置的一部分。

我正在尝试使用 dockerization 作为解决方案,但是在我的测试代码中尝试对服务器执行 运行 Perforce 命令时出现奇怪的连接错误。这是我的测试服务器代码(使用自定义 docker 图像,基于 的 Singleton 元类,并安装了 P4Python 库):

class P4TestServer(metaclass=Singleton):
    def __init__(self, conf_file='conf/p4testserver.conf'):
        self.docker_client = docker.from_env()
        self.config = P4TestServerConfig.load_config(conf_file)

        self.server_container = None

        try:
            self.server_container = self.docker_client.containers.get('perforce')
        except docker.errors.NotFound:
            self.server_container = self.docker_client.containers.run(
                'perforce-server',
                detach=True,
                environment={
                    'P4USER': self.config.p4superuser,
                    'P4PORT': self.config.p4port,
                    'P4PASSWD': self.config.p4superpasswd,
                    'NAME': self.config.p4name
                },
                name='perforce',
                ports={
                    '1667/tcp': 1667
                },
                remove=True
            )

        self.p4 = P4()
        self.p4.port = self.config.p4port
        self.p4.user = self.config.p4superuser
        self.p4.password = self.config.p4superpasswd

这是我的测试代码:

class TestSystemP4TestServer(unittest.TestCase):
    def test_server_connection(self):
        testserver = P4TestServer()
        with testserver.p4.connect():
            info = testserver.p4.run_info()
        self.assertIsNotNone(info)

这就是我遇到的问题:我第一次 运行 测试(即当它必须启动容器时),它失败并出现以下错误:

E           P4.P4Exception: [P4#run] Errors during command execution( "p4 info" )
E           
E               [Error]: 'TCP receive failed.\nread: socket: Connection reset by peer'

但是在随后的 运行s 中,当容器已经 运行ning 时,它就通过了。令人沮丧的是我无法重现此错误。如果我 运行 在任何其他上下文中测试代码,包括:

无论容器是否已经 运行ning,代码都会按预期完成。

此时我能想到的是,pytest 环境的某些 独特之处让我感到困惑,但我什至不知道如何开始诊断。有什么想法吗?

我最近遇到了类似的问题,我会启动 postgres 容器,然后立即 运行 一个 python 脚本来根据我的应用要求设置数据库。

我不得不在两个步骤之间引入一个睡眠命令,这解决了这个问题。

理想情况下,您应该在尝试使用之前检查 docker 容器的启动顺序是否完成。但对于我的本地开发用例,sleep 5 seconds 已经足够了。