pytest 执行报错:AttributeError: module 'pytest' has no attribute 'StashKey'
在一台测试机器执行pytest
命令时报错:AttributeError: module 'pytest' has no attribute 'StashKey'
从日志中看是pytest-metadata
插件调用了pytest.StashKey()
不存时报错了。
解决办法
- 方法一:
刚刚排查问题的时候通过升级pytest
版本到最新的7.3.1
解决问题了:
sudo pip3 install -U pytest
但是别着急,你可能会遇见这个问题No module named 'py.xml'; 'py' is not a package 解决办法:https://github.com/pytest-dev/pytest/issues/10428
所以我建议你看看方法二 - 方法二:
找到pytest-metadata
插件,但是我印象中始终没有手动安装过次插件啊~
通过两天研究发现在安装pytest-html
的时候会安装上pytest-metadata
,前提是你没有安装过pytest-metadata
插件,并且不管你安装什么版本的pytest-html
,都会指定安装pytest-metadata=3.0.0
.下面还温馨红字提示需要pytest
版本大于7.0.0
.
继续找到pytest-metadata
发布记录也只到1.7.0
啊,哪里来的3.0.0
(之前手动修改过pip安装源忘记是哪个)
https://github.com/davehunt/pytest-metadata/blob/master/CHANGES.rst
方法二的解决办法是卸载掉pytest-html
和pytest-metadata
这两个包,pytest
版本可以保持在6.2.5
,因为新版本的pytest
的插件有的会有更多问题.
我目前尝试比较稳定的版本组合是:
完整的安装顺序是:先安装pytest==6.2.5
,再手动安装pytest-metadata==1.7.0
,最后安装pytest-html==3.0.0
完整自动化代码:
import subprocess
import os
import re
pw = 'deepin12#$' # 当前机器sudo密码
# 卸载
uninstall_package = ['pytest','pytest-metadata','pytest-html']
uninstall_cmd= 'echo %s | sudo -S pip3 uninstall ' % pw
for x in uninstall_package:
subprocess.getoutput(cmd=uninstall_cmd + x)
# 安装
install_package = ['pytest==6.2.5','pytest-metadata==1.7.0','pytest-html==3.0.0']
install_cmd = 'echo %s | sudo -S pip3 install pytest==6.2.5' % pw
for y in install_package:
subprocess.getoutput(cmd=install_cmd + y)
# 校验
get_all_version_cmd = 'echo %s | sudo -S pip3 list' % pw
res = subprocess.getoutput(cmd=get_all_version_cmd)
# 写入文件方便后期查找
pytest_version_info_path = 'pytest_version_info.txt'
if os.path.exists(pytest_version_info_path):
os.remove(pytest_version_info_path)
with open(pytest_version_info_path,'a+') as f:
f.write(res)
# 校验执行结果
r1 = re.sub(' ', '', res)
assert 'pytest6.2.5' in r1
assert 'pytest-html3.0.0' in r1
assert 'pytest-metadata1.7.0' in r1