pytest 测试框架学习(6):pytest.importorskip

时间:2022-07-24
本文章向大家介绍pytest 测试框架学习(6):pytest.importorskip,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

pytest.importorskip

含义

importorskip: 导入并返回请求的 module 信息;如果导入的 module 不存在,则跳过当前测试。 源码:

参数分析:

  1. modname: 需要被导入的模块名称,比如 selenium;
  2. minversion: 表示需要导入的最小的版本号,如果该版本不达标,将会打印出报错信息;
  3. reason: 只有当模块没有被导入时,给定该参数将会显示出给定的消息内容。

使用

  1. 导入 selenium 模块
import pytest

class TestImportorSkip:
    def sum(self, x):
        return x + 1

    def test_importorskip(self):
        sele = pytest.importorskip("selenium")
        print(sele)
        print("skip this sum ", self.sum(4))

    def test_sum(self):
        print(self.sum(5))

执行 class,结果:

可以看到成功执行了 test_importorskip 这个方法,这是因为我们成功导入了 selenium ,并且根据打印日志显示,打印出了 selenium module 名称,并且展示了该 module 当前所在的文件的绝对路径。

  1. 设置最小版本
def test_importorskip(self):
    sele = pytest.importorskip("selenium", minversion="3.150")
    print(sele)
    print("skip this sum ", self.sum(4))

执行结果:

可以看到 该条测试已经被忽略,根据日志显示,当前我系统中存在的 selenium 版本为 3.141.0, 而我请求的最低版本为 3.150,很明显系统中存在的版本小于我要求的版本号,所以该条测试跳过未执行。

  1. 模块不存在
def test_importorskip(self):
    sele = pytest.importorskip("selenium-python")
    print(sele)
    print("skip this sum ", self.sum(4))

执行结果:

导入不存在的模块,会提示我们没有这个模块,并跳过该条测试。

  1. 指定返回消息
def test_importorskip(self):
    sele = pytest.importorskip("selenium-python", reason="当前模块导入失败")
    print(sele)
    print("skip this sum ", self.sum(4))

执行结果:

跳过该条测试,并且打印出我们所指定的需要返回的消息内容。

说明:本篇参考官网并加入自己些许理解翻译而来,觉得有用,可以点赞和赞赏哦(^ v ^),谢谢支持;如果有不足地方,可留言评论。后续将继续更新。