首页 > 解决方案 > 在 Python 单元测试中连接到本地 dockerized Perforce 服务器

问题描述

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

我正在尝试使用 dockerization 作为解决方案,但是在我的测试代码中尝试对服务器运行 Perforce 命令时出现奇怪的连接错误。这是我的测试服务器代码(使用自定义 docker 映像,基于https://stackoverflow.com/a/6798042的 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'

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

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

在这一点上,我所能想到的只是 pytest 环境有一些独特的地方让我感到困惑,但我什至不知道如何开始诊断。有什么想法吗?

标签: pythondockerpytestperforce

解决方案


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

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

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


推荐阅读