如何管理系统路径在pytest中运行系统配置验收测试

2024-05-19 06:22:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我们有一个测试框架,它稍微扩展了pytest,并将其包装在许多Ansible中,以便运行系统配置验收测试,以验证我们的基础设施是否已正确安装和配置,并且似乎运行正常。它使用Ansible打包测试,将它们发送到远程主机,然后将它们解压到virtualenv中运行测试。到目前为止,大多数人的测试都涉及在远程主机上运行命令来验证它们是否工作。你知道吗

我要测试的部分内容是一些Python模块是否已安装并工作,如果已安装并工作,请在进一步的测试中使用它们。但我在这方面有些困难,因为virtualenv(非常正确)隐藏了所有系统安装的Python模块。你知道吗

到目前为止,我的策略是运行一个subprocessshell命令/小脚本,该脚本取消设置所有与virtualenv相关的环境变量,然后使用系统Python运行一个简短的Python脚本,该脚本对其sys.path进行pickle并将其转储到stdout。你知道吗

但我不确定下一步该怎么办。在测试或设备内部处理sys.path的正确方法是什么?一旦不再需要夹具,pytest会恢复它吗?pytest如何处理测试导入的模块?它能把它们从系统模块测试完成后?你知道吗


Tags: 模块path命令脚本框架内容远程virtualenv
1条回答
网友
1楼 · 发布于 2024-05-19 06:22:53

好吧,我没有得到答案,所以我想出了这个装置来放在conftest.py

@pytest.fixture(scope="module")
def need_system_libraries():
    pycmd = 'unset VIRTUAL_ENV PYTHONPATH; exec {pyexec} -c '\
            '"import sys, pickle; sys.stdout.write(pickle.dumps(sys.path, 0))"'

    pycmd = pycmd.format(pyexec='/usr/bin/python3.7')
    _, stdout, _ = testlib.execute(pycmd)
    system_path = pickle.loads(stdout)
    # Prune any paths from the system_path that already exist in sys.path or     
    # are relative (not absolute) paths.                                         
    newsyspaths = frozenset(system_path) - frozenset(sys.path)
    newsyspaths = frozenset(path for path in newsyspaths
                            if os.path.isabs(path))
    # A set isn't ordered. Put difference back in the same order as the          
    # elements appeared in system_path. (Not needed in Python >= 3.6).           
    newsyspaths = [path for path in system_path if x in newsyspaths]
    # Save a copy of the path so we can restore it.                              
    saved_syspath = sys.path.copy()
    sys.path.extend(newsyspaths)
    # This fixture modifies the environment itself, and so doesn't need to       
    # return a value.                                                            
    yield None
    # The yield will come back when this fixture is no longer needed, so         
    # restore sys.path back to its original value. Do this by copying elements   
    # back into original sys.path in case the identity of sys.path is important  
    # somewhere deep in the bowels of Python.                                    
    sys.path[:] = saved_syspath

相关问题 更多 >

    热门问题