1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385
|
###############################################################################
#
# The MIT License (MIT)
#
# Copyright (c) typedef int GmbH
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
###############################################################################
from collections import namedtuple
from io import BytesIO, StringIO
import os
import pytest
import txaio
Log = namedtuple('Log', ['args'])
class LoggingHandler(BytesIO):
@property
def messages(self):
# Because we print the \n after, there will always be an empty
# 'message', so just don't include it.
return self.getvalue().split(os.linesep.encode('ascii'))[:-1]
_handler = LoggingHandler()
@pytest.fixture
def log_started(framework):
"""
Sets up the logging, which we can only do once per run.
"""
early_log = txaio.make_logger()
early_log.info("early log")
txaio.start_logging(out=_handler, level='debug')
@pytest.fixture(scope='function')
def handler(log_started):
"""
Resets the global TestHandler instance for each test.
"""
global _handler
_handler.truncate(0)
_handler.seek(0)
return _handler
def test_categories(handler, framework):
"""
Calling ``txaio.add_log_categories`` with a dict mapping category keys to
category log formats will allow log messages which have the
``log_category`` key take the associated format.
"""
logger = txaio.make_logger()
txaio.add_log_categories({"TX100": "{adjective} {nouns[2]}"})
# do something a little fancy, with attribute access etc.
logger.critical(
"you won't see me",
log_category="TX100",
adjective='hilarious',
nouns=['skunk', 'elephant', 'wombat'],
)
assert len(handler.messages) == 1
assert handler.messages[0].endswith(b"hilarious wombat")
def test_categories_subsequent(handler, framework):
"""
Later calls to add_log_categories update the list of log categories and
take precedence.
"""
logger = txaio.make_logger()
txaio.add_log_categories({"TX100": "{adjective} {nouns[2]}"})
txaio.add_log_categories({"TX100": "{adjective} {nouns[1]}"})
# do something a little fancy, with attribute access etc.
logger.critical(
log_category="TX100",
adjective='hilarious',
nouns=['skunk', 'elephant', 'wombat'],
)
assert len(handler.messages) == 1
assert handler.messages[0].endswith(b"hilarious elephant")
def test_critical(handler, framework):
logger = txaio.make_logger()
# do something a little fancy, with attribute access etc.
logger.critical(
"{adjective} {nouns[2]}",
adjective='hilarious',
nouns=['skunk', 'elephant', 'wombat'],
)
assert len(handler.messages) == 1
assert handler.messages[0].endswith(b"hilarious wombat")
def test_info(handler, framework):
logger = txaio.make_logger()
# do something a little fancy, with attribute access etc.
logger.info(
"{adjective} {nouns[1]}",
adjective='hilarious',
nouns=['skunk', 'elephant', 'wombat'],
)
assert len(handler.messages) == 1
assert handler.messages[0].endswith(b"hilarious elephant")
def test_legacy_error_with_traceback(handler, framework):
if framework.using_twisted:
return pytest.skip('test only for asyncio users')
import logging
try:
raise RuntimeError("the bad stuff")
except RuntimeError:
logging.error("bad stuff", exc_info=True)
assert 'RuntimeError: the bad stuff' in str(handler.messages)
def test_trace(handler, framework):
logger = txaio.make_logger()
old_log = txaio.get_global_log_level()
txaio.set_global_log_level("trace")
# the txaio_trace variable should be in it
logger.trace(
"trace {txaio_trace}",
)
txaio.set_global_log_level(old_log)
assert len(handler.messages) == 1
assert handler.messages[0].endswith(b"trace True")
def test_emit_noop(handler, framework):
"""
emit() with a too-low level is an no-op.
"""
logger = txaio.make_logger()
old_log = txaio.get_global_log_level()
txaio.set_global_log_level("info")
logger.emit("debug", "foobar")
txaio.set_global_log_level(old_log)
assert len(handler.messages) == 0
def test_emit_ok(handler, framework):
"""
emit() with an OK level emits the message.
"""
logger = txaio.make_logger()
old_log = txaio.get_global_log_level()
txaio.set_global_log_level("trace")
logger.emit("trace", "foobar")
logger.emit("info", "barbaz")
txaio.set_global_log_level(old_log)
assert len(handler.messages) == 2
assert handler.messages[0].endswith(b"foobar")
assert handler.messages[1].endswith(b"barbaz")
def test_bad_failures(handler, framework):
# just ensuring this doesn't explode
txaio.failure_format_traceback("not a failure")
txaio.failure_message("not a failure")
def test_debug_with_object(handler, framework):
logger = txaio.make_logger()
class Shape(object):
sides = 4
name = "bamboozle"
config = dict(foo='bar')
logger.info(
"{what.config[foo]} {what.sides} {what.name}",
what=Shape(),
)
assert len(handler.messages) == 1
assert handler.messages[0].endswith(b"bar 4 bamboozle")
def test_log_noop_trace(handler, framework):
# trace should be a no-op, because we set the level to 'debug' in
# the fixture
logger = txaio.make_logger()
logger.trace("a trace message")
assert len(handler.messages) == 0
def test_double_start(handler, framework):
try:
txaio.start_logging()
except RuntimeError:
assert False, "shouldn't get exception"
def test_invalid_level(framework):
try:
txaio.start_logging(level='foo')
assert False, "should get exception"
except RuntimeError as e:
assert 'Invalid log level' in str(e)
def test_class_descriptor(handler, framework):
class Something(object):
log = txaio.make_logger()
def do_a_thing(self):
self.log.info("doing a thing")
s = Something()
s.do_a_thing()
assert len(handler.messages) == 1
assert handler.messages[0].endswith(b"doing a thing")
def test_class_attribute(handler, framework):
class Something(object):
def __init__(self):
self.log = txaio.make_logger()
def do_a_thing(self):
self.log.info("doing a thing")
s = Something()
s.do_a_thing()
assert len(handler.messages) == 1
assert handler.messages[0].endswith(b"doing a thing")
def test_log_converter(handler, framework):
pytest.importorskip("twisted.logger")
# this checks that we can convert a plain Twisted Logger calling
# failure() into a traceback on our observers.
from twisted.logger import Logger
from txaio.tx import _LogObserver
out = StringIO()
observer = _LogObserver(out)
logger = Logger(observer=observer)
try:
raise RuntimeError("failed on purpose")
except RuntimeError:
logger.failure(None)
output = out.getvalue()
assert "failed on purpose" in output
assert "Traceback" in output
def test_txlog_write_binary(handler, framework):
"""
Writing to a binary stream is supported.
"""
pytest.importorskip("twisted.logger")
from txaio.tx import _LogObserver
out_file = BytesIO()
observer = _LogObserver(out_file)
observer({
"log_format": "hi: {testentry}",
"testentry": "hello",
"log_level": observer.to_tx["info"],
"log_time": 1442890018.002233
})
output = out_file.getvalue()
assert b"hi: hello" in output
def test_txlog_write_text(handler, framework_tx):
"""
Writing to a text stream is supported.
"""
pytest.importorskip("twisted.logger")
from txaio.tx import _LogObserver
out_file = StringIO()
observer = _LogObserver(out_file)
observer({
"log_format": "hi: {testentry}",
"testentry": "hello",
"log_level": observer.to_tx["info"],
"log_time": 1442890018.002233
})
output = out_file.getvalue()
assert "hi: hello" in output
def test_aiolog_write_binary(handler, framework_aio):
"""
Writing to a binary stream is supported.
"""
pytest.importorskip("txaio.aio")
from txaio.aio import _TxaioFileHandler
out_file = BytesIO()
observer = _TxaioFileHandler(out_file)
observer.emit(Log(args={
"log_message": "hi: {testentry}",
"testentry": "hello",
"log_time": 1442890018.002233
}))
output = out_file.getvalue()
assert b"hi: hello" in output
def test_aiolog_write_text(handler, framework_aio):
"""
Writing to a text stream is supported.
"""
pytest.importorskip("txaio.aio")
from txaio.aio import _TxaioFileHandler
out_file = StringIO()
observer = _TxaioFileHandler(out_file)
observer.emit(Log(args={
"log_message": "hi: {testentry}",
"testentry": "hello",
"log_time": 1442890018.002233
}))
output = out_file.getvalue()
assert "hi: hello" in output
|