Question on logger.catch()
See original GitHub issueHi! Is there a way to implement @logger.catch as a decorator for all tests, predeterming it in conftest.py in order to not to mark every my test? What i’m trying to do whit it now is:
# conftest.py
@pytest.fixture(autouse=True)
def write_logs(request):
# put logs in tests/logs
log_path = Path("Tests") / "logs"
# tidy logs in subdirectories based on test module and class names
module = request.module
class_ = request.cls
name = request.node.name + ".log"
if module:
log_path /= module.__name__.replace("tests.", "")
if class_:
log_path /= class_.__name__
log_path.mkdir(parents=True, exist_ok=True)
# append last part of the name
log_path /= name
# enable the logger
logger.remove()
logger.configure(handlers=[{"sink": log_path, "level": "TRACE", "mode": "w"}])
logger.enable("my_package")
def pytest_configure(config):
# register an additional marker
config.addinivalue_line(
"markers", "log_catcher: mark tests which we want to log"
)
def pytest_collection_modifyitems(items):
for item in items:
item.add_marker('log_catcher')
def pytest_runtest_setup(item):
if item.iter_markers(name="log_catcher"):
logger.catch(reraise=True)
# test.py
class TestFirstSuite(unittest.TestCase):
def test_01_First(self):
assert 1+1 == 3
def test_02_First(self):
print('test_02_First executed')
def test_03_First(self):
print('test_03_First executed')
but i get no logs from this in my file.log
From debugging I see that pytest collector actually “marks” all tests, but I guess this cannot work because of the incorrect usage of “logger.catch” function or just custom decorators cant work like this if I use @logger.catch right before the def_test() then everything is working ok, but I want to mark all my tests with it and at the same time I wouldnt like to mark each test. I need “fixture” which will mark all tests automatically with this decorator during test collection. Could you help me please find the way out of this problem? What am i doing wrong and what i have to do?
Issue Analytics
- State:
- Created 3 years ago
- Comments:11 (6 by maintainers)
Top GitHub Comments
Hi @PistonY.
There is inevitably a small performance penalty, at least with CPython interpreter. In the case of
logger.catch()
being used as a decorator, there is one more frame and function call due to the nested method. Also, thelogger.catch()
is implemented using context manager which has a cost. Apart from that, it’s a basictry / except
block.Overall, the cost on performances should negligible. If the part of your code is really critical, you can use instead
try / except
and thenlogger.exception()
.Thanks @Delgan .