首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在试验方法中插入卡普拉夹具的试验

在试验方法中插入卡普拉夹具的试验
EN

Stack Overflow用户
提问于 2018-05-16 14:44:13
回答 1查看 15K关注 0票数 11

对于pytest,我有以下测试类:

代码语言:javascript
复制
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夹具在像上面这样的测试类的方法中可用呢?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-05-16 15:39:57

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

代码语言:javascript
复制
# spam.py
import logging

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

spam.eggs()测试

代码语言:javascript
复制
# 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'
票数 25
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50373916

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档