pytest在试验方法中插入caplog夹具

2024-10-01 13:41:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下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 fixture可以插入到您的方法中,以便访问捕获的日志。如果我有一个添加caplog参数的测试函数,它似乎可以工作,但是如何使caplog fixture在上面这样的测试类的方法中可用呢?在


Tags: totestclientnoneifserverpytestport