python - pytest 在测试方法中插入 caplog fixture

标签 python tdd pytest

我有以下 pytest 测试类:

class TestConnection(AsyncTestCase):
      '''Integration test'''

      @gen_test
      def test_connecting_to_server(self):
          '''Connecting to the TCPserver'''
          client = server = None
          try:
              sock, port = bind_unused_port()
              with NullContext():
                  server = EchoServer()
                  server.add_socket(sock)
              client = IOStream(socket.socket())

              #### HERE I WANT TO HAVE THE caplog FIXTURE

              with ExpectLog(app_log, '.*decode.*'):
                  yield client.connect(('localhost', port))
                  yield client.write(b'hello\n')
                  # yield client.read_until(b'\n')
                  yield gen.moment
                  assert False
          finally:
              if server is not None:
                  server.stop()
              if client is not None:
                  client.close()

在这个类中显然 ExpectLog 没有工作,所以在 pytest 的文档中挖掘了一天之后,我发现有一个 caplog 固定装置,您可以将其插入到您的方法中以访问捕获的日志。如果我有一个添加了 caplog 参数的测试函数,它似乎可以工作,但是我如何使 caplog fixture 在像上面这样的测试类的方法中可用?

最佳答案

尽管您不能将固定装置作为参数传递给 unittest 测试方法,但您可以将它们作为实例属性注入(inject)。示例:

# spam.py
import logging

def eggs():
    logging.getLogger().info('bacon')

测试 spam.eggs():

# test_spam.py
import logging
import unittest
import pytest
import spam


class SpamTest(unittest.TestCase):

    @pytest.fixture(autouse=True)
    def inject_fixtures(self, caplog):
        self._caplog = caplog

    def test_eggs(self):
        with self._caplog.at_level(logging.INFO):
            spam.eggs()
            assert self._caplog.records[0].message == 'bacon'

关于python - pytest 在测试方法中插入 caplog fixture,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50373916/

相关文章:

python - 我想列出 NSE 指数中的公司

java - Junit配置错误: You must provide at least one argument for this @ParameterizedTest

python - 访问 @pytest.fixture 中的测试用例名称

pytest - 如何使用 pytest-html 在 HTML 中嵌入 base64 图像?

Angular Testing 错误 : Cannot read property 'subscribe' of undefined at new RouterLinkWithHref

python-2.7 - 如果我不将它们与我的包一起分发,如何组织我的 pytest 测试?

列表理解中的 Python any() 函数

python - 如何有一个目录对话框

python - 向 dask 数据帧添加新列会引发 ValueError : Length of values does not match length of index

c# - 单元测试——我做的对吗?