我有以下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()
Run Code Online (Sandbox Code Playgroud)
在该类中,ExpectLog显然不起作用,因此在pytest文档中进行了一天的挖掘之后,我发现可以在您的方法中插入此caplog固定装置,以访问捕获的日志。如果我有一个向其添加caplog参数的测试函数,这似乎可行,但是如何使caplog夹具在上述测试类的方法中可用?
尽管您不能将灯具作为参数传递给unittest测试方法,但是您可以将它们作为实例属性进行注入。例:
# spam.py
import logging
def eggs():
logging.getLogger().info('bacon')
Run Code Online (Sandbox Code Playgroud)
测试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'
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1938 次 |
| 最近记录: |