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 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472
|
"""
Utilities to aid unit testing L{eliot} and code that uses it.
"""
from unittest import SkipTest
from functools import wraps
from pyrsistent import PClass, field
from ._action import (
ACTION_STATUS_FIELD,
ACTION_TYPE_FIELD,
STARTED_STATUS,
FAILED_STATUS,
SUCCEEDED_STATUS,
)
from ._message import MESSAGE_TYPE_FIELD, TASK_LEVEL_FIELD, TASK_UUID_FIELD
from ._output import MemoryLogger
from . import _output
from .json import EliotJSONEncoder
COMPLETED_STATUSES = (FAILED_STATUS, SUCCEEDED_STATUS)
def issuperset(a, b):
"""
Use L{assertContainsFields} instead.
@type a: C{dict}
@type b: C{dict}
@return: Boolean indicating whether C{a} has all key/value pairs that C{b}
does.
"""
aItems = a.items()
return all(pair in aItems for pair in b.items())
def assertContainsFields(test, message, fields):
"""
Assert that the given message contains the given fields.
@param test: L{unittest.TestCase} being run.
@param message: C{dict}, the message we are checking.
@param fields: C{dict}, the fields we expect the message to have.
@raises AssertionError: If the message doesn't contain the fields.
"""
messageSubset = dict(
[(key, value) for key, value in message.items() if key in fields]
)
test.assertEqual(messageSubset, fields)
class LoggedAction(PClass):
"""
An action whose start and finish messages have been logged.
@ivar startMessage: A C{dict}, the start message contents. Also
available as C{start_message}.
@ivar endMessage: A C{dict}, the end message contents (in both success and
failure cases). Also available as C{end_message}.
@ivar children: A C{list} of direct child L{LoggedMessage} and
L{LoggedAction} instances.
"""
startMessage = field(mandatory=True)
endMessage = field(mandatory=True)
children = field(mandatory=True)
def __new__(cls, startMessage, endMessage, children):
return PClass.__new__(
cls, startMessage=startMessage, endMessage=endMessage, children=children
)
@property
def start_message(self):
return self.startMessage
@property
def end_message(self):
return self.endMessage
@classmethod
def fromMessages(klass, uuid, level, messages):
"""
Given a task uuid and level (identifying an action) and a list of
dictionaries, create a L{LoggedAction}.
All child messages and actions will be added as L{LoggedAction} or
L{LoggedMessage} children. Note that some descendant messages may be
missing if you end up logging to two or more different ILogger
providers.
@param uuid: The uuid of the task (C{unicode}).
@param level: The C{task_level} of the action's start message,
e.g. C{"/1/2/1"}.
@param messages: A list of message C{dict}s.
@return: L{LoggedAction} constructed from start and finish messages for
this specific action.
@raises: L{ValueError} if one or both of the action's messages cannot be
found.
"""
startMessage = None
endMessage = None
children = []
levelPrefix = level[:-1]
for message in messages:
if message[TASK_UUID_FIELD] != uuid:
# Different task altogether:
continue
messageLevel = message[TASK_LEVEL_FIELD]
if messageLevel[:-1] == levelPrefix:
status = message.get(ACTION_STATUS_FIELD)
if status == STARTED_STATUS:
startMessage = message
elif status in COMPLETED_STATUSES:
endMessage = message
else:
# Presumably a message in this action:
children.append(LoggedMessage(message))
elif (
len(messageLevel) == len(levelPrefix) + 2
and messageLevel[:-2] == levelPrefix
and messageLevel[-1] == 1
):
# If start message level is [1], [1, 2, 1] implies first
# message of a direct child.
child = klass.fromMessages(uuid, message[TASK_LEVEL_FIELD], messages)
children.append(child)
if startMessage is None:
raise ValueError("Missing start message")
if endMessage is None:
raise ValueError(
"Missing end message of type "
+ message.get(ACTION_TYPE_FIELD, "unknown")
)
return klass(startMessage, endMessage, children)
# PEP 8 variant:
from_messages = fromMessages
@classmethod
def of_type(klass, messages, actionType):
"""
Find all L{LoggedAction} of the specified type.
@param messages: A list of message C{dict}s.
@param actionType: A L{eliot.ActionType}, the type of the actions to
find, or the type as a C{str}.
@return: A C{list} of L{LoggedAction}.
"""
if not isinstance(actionType, str):
actionType = actionType.action_type
result = []
for message in messages:
if (
message.get(ACTION_TYPE_FIELD) == actionType
and message[ACTION_STATUS_FIELD] == STARTED_STATUS
):
result.append(
klass.fromMessages(
message[TASK_UUID_FIELD], message[TASK_LEVEL_FIELD], messages
)
)
return result
# Backwards compat:
ofType = of_type
def descendants(self):
"""
Find all descendant L{LoggedAction} or L{LoggedMessage} of this
instance.
@return: An iterable of L{LoggedAction} and L{LoggedMessage} instances.
"""
for child in self.children:
yield child
if isinstance(child, LoggedAction):
for descendant in child.descendants():
yield descendant
@property
def succeeded(self):
"""
Indicate whether this action succeeded.
@return: C{bool} indicating whether the action succeeded.
"""
return self.endMessage[ACTION_STATUS_FIELD] == SUCCEEDED_STATUS
def type_tree(self):
"""Return dictionary of all child action and message types.
Actions become dictionaries that look like
C{{<action_type>: [<child_message_type>, <child_action_dict>]}}
@return: C{dict} where key is action type, and value is list of child
types: either strings for messages, or dicts for actions.
"""
children = []
for child in self.children:
if isinstance(child, LoggedAction):
children.append(child.type_tree())
else:
children.append(child.message[MESSAGE_TYPE_FIELD])
return {self.startMessage[ACTION_TYPE_FIELD]: children}
class LoggedMessage(PClass):
"""
A message that has been logged.
@ivar message: A C{dict}, the message contents.
"""
message = field(mandatory=True)
def __new__(cls, message):
return PClass.__new__(cls, message=message)
@classmethod
def of_type(klass, messages, messageType):
"""
Find all L{LoggedMessage} of the specified type.
@param messages: A list of message C{dict}s.
@param messageType: A L{eliot.MessageType}, the type of the messages
to find, or the type as a L{str}.
@return: A C{list} of L{LoggedMessage}.
"""
result = []
if not isinstance(messageType, str):
messageType = messageType.message_type
for message in messages:
if message.get(MESSAGE_TYPE_FIELD) == messageType:
result.append(klass(message))
return result
# Backwards compat:
ofType = of_type
class UnflushedTracebacks(Exception):
"""
The L{MemoryLogger} had some tracebacks logged which were not flushed.
This means either your code has a bug and logged an unexpected
traceback. If you expected the traceback then you will need to flush it
using L{MemoryLogger.flushTracebacks}.
"""
def check_for_errors(logger):
"""
Raise exception if logger has unflushed tracebacks or validation errors.
@param logger: A L{MemoryLogger}.
@raise L{UnflushedTracebacks}: If any tracebacks were unflushed.
"""
# Check for unexpected tracebacks first, since that indicates business
# logic errors:
if logger.tracebackMessages:
raise UnflushedTracebacks(logger.tracebackMessages)
# If those are fine, validate the logging:
logger.validate()
def swap_logger(logger):
"""Swap out the global logging sink.
@param logger: An C{ILogger}.
@return: The current C{ILogger}.
"""
previous_logger = _output._DEFAULT_LOGGER
_output._DEFAULT_LOGGER = logger
return previous_logger
def validateLogging(
assertion, *assertionArgs, encoder_=EliotJSONEncoder, **assertionKwargs
):
"""
Decorator factory for L{unittest.TestCase} methods to add logging
validation.
1. The decorated test method gets a C{logger} keyword argument, a
L{MemoryLogger}.
2. All messages logged to this logger will be validated at the end of
the test.
3. Any unflushed logged tracebacks will cause the test to fail.
For example:
from unittest import TestCase
from eliot.testing import assertContainsFields, validateLogging
class MyTests(TestCase):
def assertFooLogging(self, logger):
assertContainsFields(self, logger.messages[0], {"key": 123})
@param assertion: A callable that will be called with the
L{unittest.TestCase} instance, the logger and C{assertionArgs} and
C{assertionKwargs} once the actual test has run, allowing for extra
logging-related assertions on the effects of the test. Use L{None} if you
want the cleanup assertions registered but no custom assertions.
@param assertionArgs: Additional positional arguments to pass to
C{assertion}.
@param assertionKwargs: Additional keyword arguments to pass to
C{assertion}.
@param encoder_: C{json.JSONEncoder} subclass to use when validating JSON.
"""
def decorator(function):
@wraps(function)
def wrapper(self, *args, **kwargs):
skipped = False
kwargs["logger"] = logger = MemoryLogger(encoder=encoder_)
self.addCleanup(check_for_errors, logger)
# TestCase runs cleanups in reverse order, and we want this to
# run *before* tracebacks are checked:
if assertion is not None:
self.addCleanup(
lambda: skipped
or assertion(self, logger, *assertionArgs, **assertionKwargs)
)
try:
return function(self, *args, **kwargs)
except SkipTest:
skipped = True
raise
return wrapper
return decorator
# PEP 8 variant:
validate_logging = validateLogging
def capture_logging(
assertion, *assertionArgs, encoder_=EliotJSONEncoder, **assertionKwargs
):
"""
Capture and validate all logging that doesn't specify a L{Logger}.
See L{validate_logging} for details on the rest of its behavior.
"""
def decorator(function):
@validate_logging(
assertion, *assertionArgs, encoder_=encoder_, **assertionKwargs
)
@wraps(function)
def wrapper(self, *args, **kwargs):
logger = kwargs["logger"]
previous_logger = swap_logger(logger)
def cleanup():
swap_logger(previous_logger)
self.addCleanup(cleanup)
return function(self, *args, **kwargs)
return wrapper
return decorator
def assertHasMessage(testCase, logger, messageType, fields=None):
"""
Assert that the given logger has a message of the given type, and the first
message found of this type has the given fields.
This can be used as the assertion function passed to L{validateLogging} or
as part of a unit test.
@param testCase: L{unittest.TestCase} instance.
@param logger: L{eliot.MemoryLogger} whose messages will be checked.
@param messageType: L{eliot.MessageType} indicating which message we're
looking for.
@param fields: The first message of the given type found must have a
superset of the given C{dict} as its fields. If C{None} then fields are
not checked.
@return: The first found L{LoggedMessage} of the given type, if field
validation succeeded.
@raises AssertionError: No message was found, or the fields were not
superset of given fields.
"""
if fields is None:
fields = {}
messages = LoggedMessage.ofType(logger.messages, messageType)
testCase.assertTrue(messages, "No messages of type %s" % (messageType,))
loggedMessage = messages[0]
assertContainsFields(testCase, loggedMessage.message, fields)
return loggedMessage
def assertHasAction(
testCase, logger, actionType, succeeded, startFields=None, endFields=None
):
"""
Assert that the given logger has an action of the given type, and the first
action found of this type has the given fields and success status.
This can be used as the assertion function passed to L{validateLogging} or
as part of a unit test.
@param testCase: L{unittest.TestCase} instance.
@param logger: L{eliot.MemoryLogger} whose messages will be checked.
@param actionType: L{eliot.ActionType} or C{str} indicating which message
we're looking for.
@param succeeded: Expected success status of the action, a C{bool}.
@param startFields: The first action of the given type found must have a
superset of the given C{dict} as its start fields. If C{None} then
fields are not checked.
@param endFields: The first action of the given type found must have a
superset of the given C{dict} as its end fields. If C{None} then
fields are not checked.
@return: The first found L{LoggedAction} of the given type, if field
validation succeeded.
@raises AssertionError: No action was found, or the fields were not
superset of given fields.
"""
if startFields is None:
startFields = {}
if endFields is None:
endFields = {}
actions = LoggedAction.ofType(logger.messages, actionType)
testCase.assertTrue(actions, "No actions of type %s" % (actionType,))
action = actions[0]
testCase.assertEqual(action.succeeded, succeeded)
assertContainsFields(testCase, action.startMessage, startFields)
assertContainsFields(testCase, action.endMessage, endFields)
return action
|