userver: /data/code/userver/testsuite/pytest_plugins/pytest_userver/__init__.py Source File
Loading...
Searching...
No Matches
__init__.py
1"""
2Python module pytest_userver provides testsuite support for userver services.
3
4@ingroup userver_testsuite
5"""
6
7import logging
8
9import pytest
10
11pytest.register_assert_rewrite('pytest_userver.plugins')
12
13
14# Taken from https://stackoverflow.com/a/35804945 stackoverflow answer
15def addLoggingLevel(levelName, levelNum, methodName=None):
16 """
17 Comprehensively adds a new logging level to the `logging` module and the
18 currently configured logging class.
19
20 `levelName` becomes an attribute of the `logging` module with the value
21 `levelNum`. `methodName` becomes a convenience method for both `logging`
22 itself and the class returned by `logging.getLoggerClass()` (usually just
23 `logging.Logger`). If `methodName` is not specified, `levelName.lower()` is
24 used.
25
26 To avoid accidental clobberings of existing attributes, this method will
27 raise an `AttributeError` if the level name is already an attribute of the
28 `logging` module or if the method name is already present
29
30 Example
31 -------
32 >>> addLoggingLevel('TRACE', logging.DEBUG - 5)
33 >>> logging.getLogger(__name__).setLevel("TRACE")
34 >>> logging.getLogger(__name__).trace('that worked')
35 >>> logging.trace('so did this')
36 >>> logging.TRACE
37 5
38
39 """
40 if not methodName:
41 methodName = levelName.lower()
42
43 if hasattr(logging, levelName):
44 raise AttributeError(
45 '{} already defined in logging module'.format(levelName),
46 )
47 if hasattr(logging, methodName):
48 raise AttributeError(
49 '{} already defined in logging module'.format(methodName),
50 )
51 if hasattr(logging.getLoggerClass(), methodName):
52 raise AttributeError(
53 '{} already defined in logger class'.format(methodName),
54 )
55
56 # This method was inspired by the answers to Stack Overflow post
57 # http://stackoverflow.com/q/2183233/2988730, especially
58 # http://stackoverflow.com/a/13638084/2988730
59 def logForLevel(self, message, *args, **kwargs):
60 if self.isEnabledFor(levelNum):
61 self._log(levelNum, message, args, **kwargs)
62
63 def logToRoot(message, *args, **kwargs):
64 logging.log(levelNum, message, *args, **kwargs)
65
66 logging.addLevelName(levelNum, levelName)
67 setattr(logging, levelName, levelNum)
68 setattr(logging.getLoggerClass(), methodName, logForLevel)
69 setattr(logging, methodName, logToRoot)
70
71
72if not hasattr(logging, 'TRACE'):
73 addLoggingLevel('TRACE', logging.DEBUG - 5)