pytest 在测试方法中插入 caplog 夹具 [英] pytest to insert caplog fixture in test method

查看:138
本文介绍了pytest 在测试方法中插入 caplog 夹具的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下 pytest 测试类:

I have the following test class for 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 固定装置在上述测试类的方法中可用?

Within this class apparently ExpectLog is not working so after a day of digging around in pytest's documentation I found that there is this caplog fixture that you can have inserted in you methods in order to access the captured logs. It seems to work if I have a test function to which I add the caplog argument but how do I make the caplog fixture available within the methods of a test class like the one above?

推荐答案

虽然您不能将夹具作为参数传递给 unittest 测试方法,但您可以将它们作为实例属性注入.示例:

Although you can't pass fixtures as parameters to unittest test methods, you can inject them as instance attributes. Example:

# 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'

这篇关于pytest 在测试方法中插入 caplog 夹具的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆