Pytest如何防止导入包失败即importorskip的用法
  TEZNKK3IfmPf 2023年11月14日 82 0
 

一、导入失败时所有用例标记自动标记为skip

在写自动化脚本的时候,若存在导入的包作为被测对象而导入包都有可能失败的情况下,或者包尚未开发完成,在提前开发自动化脚本时,那么如果按照正常的导入包逻辑,开发出的自动化脚本是无法运行的,pytest提供了importorskip的内置的标签,用于当导入包失败时,自动将当前文件中的测试脚本标记为skipped状态。
如下脚本,导入numpy库,因为当前的环境尚未安装numpy库,因此这里会导入失败,此时pytest会自动将当前文件的测试函数全部标记为skipped。

import pytest

np=pytest.importorskip("numpy")

def test_01():
    print(dir(np))
    assert 1==1

执行结果如下:

pytest -s
========================================================================= test session starts ========================================================================== 
platform win32 -- Python 3.9.13, pytest-7.1.2, pluggy-1.0.0
rootdir: D:\redrose2100-book\ebooks\Pytest企业级应用实战\src
collected 0 items / 1 skipped

========================================================================== 1 skipped in 0.08s =========================================================================

二、导入成功时,返回值即为导入的模块对象

使用pytest.importorskip 方法导入模块时,当某块存在并且导入成功时,返回值即是导入的模块对象,换言之,可以直接将返回值赋值给一个对象,而在接下来的测试脚本中直接通过此对象调用导入模块的方法,编写测试代码如下,这里修改为导入math库

import pytest

math=pytest.importorskip("math")

def test_01():
    print(dir(math))
    assert 1==1

执行结果如下,即此时导入成功,math变量即导入的math库,在测试函数中可以看出打印出的都是math库的方法或属性。

pytest -s
========================================================================= test session starts ==========================================================================
platform win32 -- Python 3.9.13, pytest-7.1.2, pluggy-1.0.0
rootdir: D:\redrose2100-book\ebooks\Pytest企业级应用实战\src
collected 1 item

test_demo.py ['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'comb', 'copysign', 'co s', 'cosh', 'degrees', 'dist', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isf inite', 'isinf', 'isnan', 'isqrt', 'lcm', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'nextafter', 'perm', 'pi', 'pow', 'prod', 'radians', 'remain der', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc', 'ulp']
.

========================================================================== 1 passed in 2.37s =========================================================================== 
【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月14日 0

暂无评论

TEZNKK3IfmPf