python - 在 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'
但是在随后的运行中,当容器已经在运行时,它就会通过。令人沮丧的是,我无法以其他方式重现此错误。如果我在任何其他上下文中运行该测试代码,包括:
- 在 Python 解释器中
testserver.p4.run_info()
在调用之前停止的调试器中
无论容器是否已经运行,代码都会按预期完成。
在这一点上,我所能想到的只是 pytest 环境有一些独特的地方让我感到困惑,但我什至不知道如何开始诊断。有什么想法吗?
解决方案
我最近遇到了类似的问题,我将启动 postgres 容器,然后根据我的应用程序要求立即运行 python 脚本来设置数据库。
我不得不在这两个步骤之间引入一个 sleep 命令,这解决了这个问题。
理想情况下,您应该在尝试使用之前检查 docker 容器的启动顺序是否已完成。但对于我的本地开发用例,睡眠 5 秒就足够了。
推荐阅读
- java - 如何使用线程安全方法使用多个类填充 Map
- angular - 如何在 NGRX 中每次使用不同的参数触发相同的 API 并聚合响应?
- python - 在http服务器python上显示png图像
- python - 使用spyder调试时如何使用变量
- matlab - 切换案例:从另一个案例中转到“否则”
- django - 无法使用 Nginix 和 Daphne 实现 websocket
- c# - 如何将两个对象列表与不规则的顺序进行比较?
- pandas - 如何用python可视化层次结构df?
- android - 给定组件 multidex.MultiDexApplication 没有实现接口 dagger.hilt.internal
- ios - CLLocationManager.RegionEntered() 事件未在 Xamarin iOS 中触发