浅谈Pytest中的warning处理

浅谈,pytest,warning,处理 · 浏览次数 : 51

小编点评

Sure, here's a summary of the provided text: **Problem:** * Pytest doesn't handle warnings properly and displays them in the console. **Solution:** * Use the `warnings.filterwarnings()` function to control which warnings are displayed. * Set the `filterwarnings` parameter to `'ignore'` when calling `pytest.main()`. **Explanation:** * `warnings.filterwarnings()` allows you to specify which warnings to display and which to suppress. * By setting `filterwarnings` to `'ignore'`, only warnings related to `DeprecationWarning` are displayed. * This ensures that other types of warnings are still shown. **Example:** ```python import pytest def test_demo(): warnings.filterwarnings('ignore', 'DeprecationWarning') assert True if __name__ == '__main__': pytest.main(['-sv', '__file__']) ``` **Output:** When running the script, you should see only warnings related to `DeprecationWarning` in the console: ``` test_demo .............................................................................. test_demo.py:5: DeprecationWarning: test warn ---------------------------------------------------------------------- warnings summary =============================== testCases/test_demo.py::test_demo test_demo.py:5: DeprecationWarning: test warn ---------------------------------------------------------------------- 1 passed, 1 warning in 0.09s ``` **Note:** * `filterwarnings` can be used with other warning levels, such as `'error'` for all errors. * The `--disable-warnings` and `--disable-pytest-warnings` options disable warnings summary and pytest-specific warnings, respectively.

正文

浅谈Pytest中的warning处理

没有处理warning

  • 我们写一个简单的测试
import pytest

def test_demo():
    import warnings
    warnings.warn('test warn',DeprecationWarning)
    assert True


if __name__ == '__main__':
    pytest.main(['-sv',__file__])
  • 你运行的话会有如下提示
============================= test session starts =============================
platform win32 -- Python 3.9.6, pytest-7.1.2, pluggy-1.0.0 -- D:\Python39\python.exe
cachedir: .pytest_cache
metadata: ...
rootdir: D:\pythonProject\AutoTest\PytestTemp, configfile: pytest.ini
plugins: ...
collecting ... collected 1 item

test_demo.py::test_demo PASSED

============================== warnings summary ===============================
testCases/test_demo.py::test_demo
  test_demo.py:5: DeprecationWarning: test warn
    warnings.warn('test warn',DeprecationWarning)

-- Docs: https://docs.pytest.org/en/stable/how-to/capture-warnings.html
======================== 1 passed, 1 warning in 0.05s =========================

进程已结束,退出代码为 0

  • warning在pytest3.1之后会在执行期间捕获,初学者多见于mark漏了标记,可以参考浅谈Pytest中的marker

-W 命令行及处理

  • pytest提供了一个命令行参数-W

    -W PYTHONWARNINGS, --pythonwarnings=PYTHONWARNINGS   
       含义:  set which warnings to report, see -W option of python itself.
    
  • python的-W

    -W arg : warning control; arg is action:message:category:module:lineno  also PYTHONWARNINGS=arg
    

    https://docs.python.org/3/library/warnings.html#warning-filter

  • 关于格式说明

    • action is one of the following strings:

      Value Disposition
      "default" print the first occurrence of matching warnings for each location (module + line number) where the warning is issued
      "error" turn matching warnings into exceptions
      "ignore" never print matching warnings
      "always" always print matching warnings
      "module" print the first occurrence of matching warnings for each module where the warning is issued (regardless of line number)
      "once" print only the first occurrence of matching warnings, regardless of location
    • message is a string containing a regular expression that the start of the warning message must match, case-insensitively. In -W and PYTHONWARNINGS, message is a literal string that the start of the warning message must contain (case-insensitively), ignoring any whitespace at the start or end of message.

    • category is a class (a subclass of Warning) of which the warning category must be a subclass in order to match.

    • module is a string containing a regular expression that the start of the fully qualified module name must match, case-sensitively. In -W and PYTHONWARNINGS, module is a literal string that the fully qualified module name must be equal to (case-sensitively), ignoring any whitespace at the start or end of module.

    • lineno is an integer that the line number where the warning occurred must match, or 0 to match all line numbers.


  • 增加命令行处理

    # action:message:category:module:lineno   # 注意格式
    -W error::DeprecationWarning  # 意思是看到DeprecationWarning就把它当做是一个error
    
    ================================== FAILURES ===================================
    __________________________________ test_demo __________________________________
    
        def test_demo():
            import warnings
    >       warnings.warn('test warn',DeprecationWarning)
    E       DeprecationWarning: test warn
    
    test_demo.py:5: DeprecationWarning
    =========================== short test summary info ===========================
    FAILED test_demo.py::test_demo - DeprecationWarning: test warn
    ============================== 1 failed in 0.09s ==============================
    
    
  • 可以看到case变成了failed


  • 换一下,改为ignore,case就PASSED了

    pytest.main(['-sv','-W ignore::DeprecationWarning',__file__])
    
    ============================== 1 passed in 0.07s ==============================
    

等价的装饰器pytest.mark.filterwarnings

  • 命令行的做法也可以等价到装饰器的写法,跟大多数的插件类似,命令行是针对所有的,装饰器是针对某个case的

    @pytest.mark.filterwarnings('ignore::DeprecationWarning')  # 装饰在被测函数上即可
    
    @pytest.mark.filterwarnings('error::DeprecationWarning')
    
    

等价的pytest.ini中的filterwarnings

  • 你也可以这样写一个pytest.ini

    [pytest]
    filterwarnings:
        ignore::DeprecationWarning
    
    
  • 或者这样

    [pytest]
    filterwarnings:
        error::DeprecationWarning
    
    

  • 还可以这样

    [pytest]
    filterwarnings:
        error
        ignore::DeprecationWarning
    
    

    这个意思是,所有的warning都被处理成error,但忽略DeprecationWarning。

    注意:当警告与列表中的多个选项匹配时,将执行最后一个匹配选项的操作。

关于warning的其他

  • --disable-warnings命令行选项可以禁用warning summary

    ============================== warnings summary ===============================
    testCases/test_demo.py::test_demo
      test_demo.py:5: DeprecationWarning: test warn
        warnings.warn('test warn',DeprecationWarning)
    
    -- Docs: https://docs.pytest.org/en/stable/how-to/capture-warnings.html
    
    
  • 上面的warning加了命令行之后就没了

  • 命令行的解释

      --disable-warnings, --disable-pytest-warnings  : disable warnings summary
                            
    
    

  • 还有一个命令行-pno:warnings,完全禁用警告捕获

    pytest.main(['-sv','-pno:warnings',__file__])
    
    
  • 实测-pno:warnings的pno要挨在一起,这有点...

  • 命令行的解释

      -p name               early-load given plugin module name or
                            entry point (multi-allowed).
                            To avoid loading of plugins, use the
                            `no:` prefix, e.g. `no:doctest`.
    
    
  • 如果你放在pytest.ini中的pno就可分可合(离谱)

    [pytest]
    addopts = -p no:warnings # -pno:warnings
    
    

与浅谈Pytest中的warning处理相似的内容:

浅谈Pytest中的warning处理

浅谈Pytest中的warning处理 没有处理warning 我们写一个简单的测试 import pytest def test_demo(): import warnings warnings.warn('test warn',DeprecationWarning) assert True if

浅谈Pytest中的marker

浅谈Pytest中的marker 没有注册marker 我们写一个简单的测试 # test_demo.py import pytest @pytest.mark.login def test_demo(): assert True 你运行的话会有如下提示 test_demo.py:4: Pytest

浅谈k8s中cni0和docker0的关系和区别

最近在复习k8s网络方面的知识,查看之前学习时整理的笔记和文档还有过往自己总结的博客之后发现一个问题,就是在有关flannel和calico这两个k8s网络插件的文章和博客中,会涉及到cni0和docker0这两个网桥设备,但是都没有明确说明他们俩之间的关系,有的甚至将两者混为一谈,这也是我之前的学

浅谈性能测试稳定性 Constant Throughput Timer(常数吞吐量定时器)

在性能测试过程中总会收到一些需求如:单接口每秒并发20,这种并发持续60秒,通过负载测试查看系统稳定性,今天就让我们来浅谈一下这种场景如何去实现性能测试~

浅谈如何向上管理

最近听说了很多事,加之目前自己也处在被汇报以及需要向上汇报的状态中间,迫使我开始思考向上管理(managing up)这个话题。这是一个有争议的话题,很多人(包括曾经的自己)下意识的会将向上管理与徒有其表的讨好或者迎合这类负面词划上等号。借此契机在查阅了很多资料之后,才意识到它不过是一项职场软技能而已。

[转帖]浅谈系统稳定性与高可用保障的几种思路

https://segmentfault.com/u/dewujishu 一、前言 高并发、高可用、高性能被称为互联网三高架构,这三者都是工程师和架构师在系统架构设计中必须考虑的因素之一。今天我们就来聊一聊三H中的高可用,也是我们常说的系统稳定性。 本篇文章只聊思路,没有太多的深入细节。阅读全文大概

[转帖]浅谈RAID写惩罚(Write Penalty)与IOPS计算

介绍 通常在讨论不同RAID保护类型的性能的时候,结论都会是RAID-1提供比较好的读写性能,RAID-5读性能不错,但是写入性能就不如RAID-1,RAID-6保护级别更高,但写性能相对更加差,RAID10是提供最好的性能和数据保护,不过成本最高等等。其实决定这些性能考虑的因素很简单,它就是RAI

[转帖]浅谈RAID写惩罚(Write Penalty)与IOPS计算_文字版

https://www.cnblogs.com/IvanChen/p/4491984.html 介绍 通常在讨论不同RAID保护类型的性能的时候,结论都会是RAID-1提供比较好的读写性能,RAID-5读性能不错,但是写入性能就不如RAID-1,RAID-6保护级别更高,但写性能相对更加差,RAID

[转帖]张磊:浅谈容器网络

https://zhuanlan.zhihu.com/p/595014129 你好,我是张磊。今天我和你分享的主题是:浅谈容器网络。 在前面讲解容器基础时,我曾经提到过一个Linux容器能看见的“网络栈”,实际上是被隔离在它自己的Network Namespace当中的。 而所谓“网络栈”,就包括了

[转帖]浅谈Armv8-A处理器

https://www.elecfans.com/emb/dsp/202208291886182.html 众所周知,ARM是一家设计并授权处理器和相应IP(比如互连总线,中断处理器,图像处理器等等)的公司,目前其处理器产品分为三类: Cortex-A系列:这个系列主要是应用(Application