【问题标题】:Where does pytest.skip('Output string') get printed?pytest.skip('Output string') 在哪里打印?
【发布时间】:2020-11-10 19:50:55
【问题描述】:

我在名为 test_me.py 的 python 模块中有以下代码:

@pytest.fixture()
def test_me():
     if condition:
        pytest.skip('Test Message')

def test_func(test_me):
    assert ...

输出如下:

tests/folder/test_me.py::test_me SKIPPED

问题:“测试消息”在哪里打印或输出?我在任何地方都看不到或找不到它。

【问题讨论】:

  • 我打算让你参考官方文档,但它似乎没有解释这一点。
  • @KarlKnechtel 完全正确。我从原始文档中得到了使用此功能的想法,但它似乎并没有像我预期的那样工作。

标签: python


【解决方案1】:

根据Pytest documentation,可以使用-rs标志来显示。

$ pytest -rs
======================== test session starts ========================
platform darwin -- Python 3.7.6, pytest-6.1.2, py-1.9.0, pluggy-0.13.1
rootdir: ...
collected 1 item                                                    

test_sample.py s                                              [100%]

====================== short test summary info ======================
SKIPPED [1] test_sample.py:5: Test Message
======================== 1 skipped in 0.02s =========================
import pytest

@pytest.fixture()
def test_me():
   pytest.skip('Test Message')

def test_1(test_me):
   pass

不确定这是否是特定于平台的,或者它是否适用于 OP 配置,因为 OP 没有提供任何具体信息。

【讨论】:

  • 这回答了这个问题。谢谢你。它适用于 Ubuntu。
【解决方案2】:

我认为在测试运行期间没有任何内置方式可以打印这些消息。另一种方法是创建自己的跳过函数:

def skip(message):
    print(message)  # you can add some additional info around the message
    pytest.skip()

@pytest.fixture()
def test_me():
     if condition:
        skip('Test Message')

你也可以把这个自定义函数变成一个装饰器。

【讨论】:

    【解决方案3】:

    粗略地看一下 pytest 的代码,可以发现它被封装为异常消息,该异常消息是在调用 skip() 本身之后引发的。它的行为虽然没有明确记录,但在 outcomes.py 中定义:

    def skip(msg: str = "", *, allow_module_level: bool = False) -> "NoReturn":
        """Skip an executing test with the given message.
        This function should be called only during testing (setup, call or teardown) or
        during collection by using the ``allow_module_level`` flag.  This function can
        be called in doctests as well.
        :param bool allow_module_level:
            Allows this function to be called at module level, skipping the rest
            of the module. Defaults to False.
        .. note::
            It is better to use the :ref:`pytest.mark.skipif ref` marker when
            possible to declare a test to be skipped under certain conditions
            like mismatching platforms or dependencies.
            Similarly, use the ``# doctest: +SKIP`` directive (see `doctest.SKIP
            <https://docs.python.org/3/library/doctest.html#doctest.SKIP>`_)
            to skip a doctest statically.
        """
        __tracebackhide__ = True
        raise Skipped(msg=msg, allow_module_level=allow_module_level)
    

    最终,这个异常被包裹了好几层,最后被抛出为BaseException。因此,您应该能够通过捕获相关异常并读取其异常消息 (relevant SO thread) 来访问消息本身。

    【讨论】:

      猜你喜欢
      • 2010-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多