【问题标题】:pytest: printing from fixturepytest:从夹具打印
【发布时间】:2016-01-16 11:58:42
【问题描述】:

我正在使用 Pytest 编写测试。我有一个这样的夹具:

@pytest.yield_fixture(autouse=True, scope='session')
def manage_tests():
    print("Do stuff...")
    do_stuff()
    yield

我在那里放了一个打印语句,以便在运行测试时可以在控制台中看到它,以便更好地了解程序正在做什么。但我在控制台中看不到该文本,我猜 pytest 会吞下它。有什么方法可以从灯具打印吗?

【问题讨论】:

    标签: python pytest


    【解决方案1】:

    Pytest 不会吞下输出,它只是默认不显示。要在控制台中查看输出,请尝试使用 -s 选项运行测试,例如:

    pytest -s <path_to_file>
    

    【讨论】:

      【解决方案2】:

      使用 pytest 3 使用这个夹具:

      @pytest.fixture()
      def tprint(request, capsys):
          """Fixture for printing info after test, not supressed by pytest stdout/stderr capture"""
          lines = []
          yield lines.append
      
          with capsys.disabled():
              for line in lines:
                  sys.stdout.write('\n{}'.format(line))
      

      【讨论】:

        【解决方案3】:

        我可以看到打印语句。但有几点需要注意:

        • 因为你有scope=session,所以这只在第一次测试时执行。
        • 如果第一个测试通过,则不会打印任何内容。您可以使用命令行选项-s 强制打印标准输出(==不被 pytest 捕获)。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2023-03-11
          • 1970-01-01
          • 2021-03-13
          • 2020-06-04
          • 2019-07-13
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多