pytest 在测试方法中插入 caplog fixture
pytest to insert caplog fixture in test method
我对 pytest 进行了以下测试 class:
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()
在这个 class 中显然 ExpectLog 没有工作所以在 pytest 的文档中挖掘了一天之后我发现有这个 caplog fixture 你可以插入你的方法以访问捕获的日志.如果我有一个添加 caplog 参数的测试函数,它似乎可以工作,但是我如何使 caplog 夹具在测试方法中可用 class 就像上面的那样?
虽然您不能将固定装置作为参数传递给 unittest
测试方法,但您可以将它们作为实例属性注入。示例:
# 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 进行了以下测试 class:
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()
在这个 class 中显然 ExpectLog 没有工作所以在 pytest 的文档中挖掘了一天之后我发现有这个 caplog fixture 你可以插入你的方法以访问捕获的日志.如果我有一个添加 caplog 参数的测试函数,它似乎可以工作,但是我如何使 caplog 夹具在测试方法中可用 class 就像上面的那样?
虽然您不能将固定装置作为参数传递给 unittest
测试方法,但您可以将它们作为实例属性注入。示例:
# 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'