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 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051
|
"""
Tests for L{eliot.testing}.
"""
from unittest import SkipTest, TestResult, TestCase, skipUnless
try:
import numpy as np
except ImportError:
np = None
from ..testing import (
issuperset,
assertContainsFields,
LoggedAction,
LoggedMessage,
validateLogging,
UnflushedTracebacks,
assertHasMessage,
assertHasAction,
validate_logging,
capture_logging,
swap_logger,
check_for_errors,
)
from .._output import MemoryLogger
from .._action import start_action
from .._message import Message
from .._validation import ActionType, MessageType, ValidationError, Field
from .._traceback import write_traceback
from .. import add_destination, remove_destination, _output, log_message
from .common import CustomObject, CustomJSONEncoder
class IsSuperSetTests(TestCase):
"""
Tests for L{issuperset}.
"""
def test_equal(self):
"""
Equal dictionaries are supersets of each other.
"""
a = {"a": 1}
b = a.copy()
self.assertTrue(issuperset(a, b))
def test_additionalIsSuperSet(self):
"""
If C{A} is C{B} plus some extra entries, C{A} is superset of C{B}.
"""
a = {"a": 1, "b": 2, "c": 3}
b = {"a": 1, "c": 3}
self.assertTrue(issuperset(a, b))
def test_missingIsNotSuperSet(self):
"""
If C{A} is C{B} minus some entries, C{A} is not a superset of C{B}.
"""
a = {"a": 1, "c": 3}
b = {"a": 1, "b": 2, "c": 3}
self.assertFalse(issuperset(a, b))
class LoggedActionTests(TestCase):
"""
Tests for L{LoggedAction}.
"""
def test_values(self):
"""
The values given to the L{LoggedAction} constructor are stored on it.
"""
d1 = {"x": 1}
d2 = {"y": 2}
root = LoggedAction(d1, d2, [])
self.assertEqual((root.startMessage, root.endMessage), (d1, d2))
def fromMessagesIndex(self, messages, index):
"""
Call L{LoggedAction.fromMessages} using action specified by index in
a list of message dictionaries.
@param messages: A C{list} of message dictionaries.
@param index: Index to the logger's messages.
@return: Result of L{LoggedAction.fromMessages}.
"""
uuid = messages[index]["task_uuid"]
level = messages[index]["task_level"]
return LoggedAction.fromMessages(uuid, level, messages)
def test_fromMessagesCreatesLoggedAction(self):
"""
L{LoggedAction.fromMessages} returns a L{LoggedAction}.
"""
logger = MemoryLogger()
with start_action(logger, "test"):
pass
logged = self.fromMessagesIndex(logger.messages, 0)
self.assertIsInstance(logged, LoggedAction)
def test_fromMessagesStartAndSuccessfulFinish(self):
"""
L{LoggedAction.fromMessages} finds the start and successful finish
messages of an action and stores them in the result.
"""
logger = MemoryLogger()
Message.new(x=1).write(logger)
with start_action(logger, "test"):
Message.new(x=1).write(logger)
# Now we should have x message, start action message, another x message
# and finally finish message.
logged = self.fromMessagesIndex(logger.messages, 1)
self.assertEqual(
(logged.startMessage, logged.endMessage),
(logger.messages[1], logger.messages[3]),
)
def test_fromMessagesStartAndErrorFinish(self):
"""
L{LoggedAction.fromMessages} finds the start and successful finish
messages of an action and stores them in the result.
"""
logger = MemoryLogger()
try:
with start_action(logger, "test"):
raise KeyError()
except KeyError:
pass
logged = self.fromMessagesIndex(logger.messages, 0)
self.assertEqual(
(logged.startMessage, logged.endMessage),
(logger.messages[0], logger.messages[1]),
)
def test_fromMessagesStartNotFound(self):
"""
L{LoggedAction.fromMessages} raises a L{ValueError} if a start message
is not found.
"""
logger = MemoryLogger()
with start_action(logger, action_type="test"):
pass
self.assertRaises(ValueError, self.fromMessagesIndex, logger.messages[1:], 0)
def test_fromMessagesFinishNotFound(self):
"""
L{LoggedAction.fromMessages} raises a L{ValueError} if a finish message
is not found.
"""
logger = MemoryLogger()
with start_action(logger, action_type="test"):
pass
with self.assertRaises(ValueError) as cm:
self.fromMessagesIndex(logger.messages[:1], 0)
self.assertEqual(cm.exception.args[0], "Missing end message of type test")
def test_fromMessagesAddsChildMessages(self):
"""
L{LoggedAction.fromMessages} adds direct child messages to the
constructed L{LoggedAction}.
"""
logger = MemoryLogger()
# index 0:
Message.new(x=1).write(logger)
# index 1 - start action
with start_action(logger, "test"):
# index 2
Message.new(x=2).write(logger)
# index 3
Message.new(x=3).write(logger)
# index 4 - end action
# index 5
Message.new(x=4).write(logger)
logged = self.fromMessagesIndex(logger.messages, 1)
expectedChildren = [
LoggedMessage(logger.messages[2]),
LoggedMessage(logger.messages[3]),
]
self.assertEqual(logged.children, expectedChildren)
def test_fromMessagesAddsChildActions(self):
"""
L{LoggedAction.fromMessages} recursively adds direct child actions to
the constructed L{LoggedAction}.
"""
logger = MemoryLogger()
# index 0
with start_action(logger, "test"):
# index 1:
with start_action(logger, "test2"):
# index 2
Message.new(message_type="end", x=2).write(logger)
# index 3 - end action
with start_action(logger, "test3"):
# index 4
pass
# index 5 - end action
# index 6 - end action
logged = self.fromMessagesIndex(logger.messages, 0)
self.assertEqual(logged.children[0], self.fromMessagesIndex(logger.messages, 1))
self.assertEqual(
logged.type_tree(), {"test": [{"test2": ["end"]}, {"test3": []}]}
)
def test_ofType(self):
"""
L{LoggedAction.ofType} returns a list of L{LoggedAction} created by the
specified L{ActionType}.
"""
ACTION = ActionType("myaction", [], [], "An action!")
logger = MemoryLogger()
# index 0
with start_action(logger, "test"):
# index 1:
with ACTION(logger):
# index 2
Message.new(x=2).write(logger)
# index 3 - end action
# index 4 - end action
# index 5
with ACTION(logger):
pass
# index 6 - end action
logged = LoggedAction.ofType(logger.messages, ACTION)
self.assertEqual(
logged,
[
self.fromMessagesIndex(logger.messages, 1),
self.fromMessagesIndex(logger.messages, 5),
],
)
# String-variant of ofType:
logged2 = LoggedAction.ofType(logger.messages, "myaction")
self.assertEqual(logged, logged2)
def test_ofTypeNotFound(self):
"""
L{LoggedAction.ofType} returns an empty list if actions of the given
type cannot be found.
"""
ACTION = ActionType("myaction", [], [], "An action!")
logger = MemoryLogger()
self.assertEqual(LoggedAction.ofType(logger.messages, ACTION), [])
def test_descendants(self):
"""
L{LoggedAction.descendants} returns all descendants of the
L{LoggedAction}.
"""
ACTION = ActionType("myaction", [], [], "An action!")
logger = MemoryLogger()
# index 0
with ACTION(logger):
# index 1:
with start_action(logger, "test"):
# index 2
Message.new(x=2).write(logger)
# index 3 - end action
# index 4
Message.new(x=2).write(logger)
# index 5 - end action
loggedAction = LoggedAction.ofType(logger.messages, ACTION)[0]
self.assertEqual(
list(loggedAction.descendants()),
[
self.fromMessagesIndex(logger.messages, 1),
LoggedMessage(logger.messages[2]),
LoggedMessage(logger.messages[4]),
],
)
def test_succeeded(self):
"""
If the action succeeded, L{LoggedAction.succeeded} will be true.
"""
logger = MemoryLogger()
with start_action(logger, "test"):
pass
logged = self.fromMessagesIndex(logger.messages, 0)
self.assertTrue(logged.succeeded)
def test_notSucceeded(self):
"""
If the action failed, L{LoggedAction.succeeded} will be false.
"""
logger = MemoryLogger()
try:
with start_action(logger, "test"):
raise KeyError()
except KeyError:
pass
logged = self.fromMessagesIndex(logger.messages, 0)
self.assertFalse(logged.succeeded)
class LoggedMessageTest(TestCase):
"""
Tests for L{LoggedMessage}.
"""
def test_values(self):
"""
The values given to the L{LoggedMessage} constructor are stored on it.
"""
message = {"x": 1}
logged = LoggedMessage(message)
self.assertEqual(logged.message, message)
def test_ofType(self):
"""
L{LoggedMessage.ofType} returns a list of L{LoggedMessage} created by the
specified L{MessageType}.
"""
MESSAGE = MessageType("mymessage", [], "A message!")
logger = MemoryLogger()
# index 0
MESSAGE().write(logger)
# index 1
Message.new(x=2).write(logger)
# index 2
MESSAGE().write(logger)
logged = LoggedMessage.ofType(logger.messages, MESSAGE)
self.assertEqual(
logged,
[LoggedMessage(logger.messages[0]), LoggedMessage(logger.messages[2])],
)
# Lookup by string type:
logged2 = LoggedMessage.ofType(logger.messages, "mymessage")
self.assertEqual(logged, logged2)
def test_ofTypeNotFound(self):
"""
L{LoggedMessage.ofType} returns an empty list if messages of the given
type cannot be found.
"""
MESSAGE = MessageType("mymessage", [], "A message!")
logger = MemoryLogger()
self.assertEqual(LoggedMessage.ofType(logger.messages, MESSAGE), [])
class AssertContainsFields(TestCase):
"""
Tests for L{assertContainsFields}.
"""
class ContainsTest(TestCase):
"""
A test case that uses L{assertContainsFields}.
"""
def __init__(self, message, expectedFields):
TestCase.__init__(self)
self.message = message
self.expectedFields = expectedFields
def runTest(self):
assertContainsFields(self, self.message, self.expectedFields)
def test_equal(self):
"""
Equal dictionaries contain each other.
"""
message = {"a": 1}
expected = message.copy()
test = self.ContainsTest(message, expected)
# No exception raised:
test.debug()
def test_additionalIsSuperSet(self):
"""
If C{A} is C{B} plus some extra entries, C{A} contains the fields in
C{B}.
"""
message = {"a": 1, "b": 2, "c": 3}
expected = {"a": 1, "c": 3}
test = self.ContainsTest(message, expected)
# No exception raised:
test.debug()
def test_missingFields(self):
"""
If C{A} is C{B} minus some entries, C{A} does not contain the fields in
C{B}.
"""
message = {"a": 1, "c": 3}
expected = {"a": 1, "b": 2, "c": 3}
test = self.ContainsTest(message, expected)
self.assertRaises(AssertionError, test.debug)
def test_differentValues(self):
"""
If C{A} has a different value for a specific field than C{B}, C{A} does
not contain the fields in C{B}.
"""
message = {"a": 1, "c": 3}
expected = {"a": 1, "c": 2}
test = self.ContainsTest(message, expected)
self.assertRaises(AssertionError, test.debug)
class ValidateLoggingTestsMixin(object):
"""
Tests for L{validateLogging} and L{capture_logging}.
"""
validate = None
def test_decoratedFunctionCalledWithMemoryLogger(self):
"""
The underlying function decorated with L{validateLogging} is called with
a L{MemoryLogger} instance.
"""
result = []
class MyTest(TestCase):
@self.validate(None)
def test_foo(this, logger):
result.append((this, logger.__class__))
theTest = MyTest("test_foo")
theTest.run()
self.assertEqual(result, [(theTest, MemoryLogger)])
def test_decorated_function_passthrough(self):
"""
Additional arguments are passed to the underlying function.
"""
result = []
def another_wrapper(f):
def g(this):
f(this, 1, 2, c=3)
return g
class MyTest(TestCase):
@another_wrapper
@self.validate(None)
def test_foo(this, a, b, logger, c=None):
result.append((a, b, c))
theTest = MyTest("test_foo")
theTest.debug()
self.assertEqual(result, [(1, 2, 3)])
def test_newMemoryLogger(self):
"""
The underlying function decorated with L{validateLogging} is called with
a new L{MemoryLogger} every time the wrapper is called.
"""
result = []
class MyTest(TestCase):
@self.validate(None)
def test_foo(this, logger):
result.append(logger)
theTest = MyTest("test_foo")
theTest.run()
theTest.run()
self.assertIsNot(result[0], result[1])
def test_returns(self):
"""
The result of the underlying function is returned by wrapper when called.
"""
class MyTest(TestCase):
@self.validate(None)
def test_foo(self, logger):
return 123
self.assertEqual(MyTest("test_foo").test_foo(), 123)
def test_raises(self):
"""
The exception raised by the underlying function is passed through by the
wrapper when called.
"""
exc = Exception()
class MyTest(TestCase):
@self.validate(None)
def test_foo(self, logger):
raise exc
raised = None
try:
MyTest("test_foo").debug()
except Exception as e:
raised = e
self.assertIs(exc, raised)
def test_name(self):
"""
The wrapper has the same name as the wrapped function.
"""
class MyTest(TestCase):
@self.validate(None)
def test_foo(self, logger):
pass
self.assertEqual(MyTest.test_foo.__name__, "test_foo")
def test_addCleanupValidate(self):
"""
When a test method is decorated with L{validateLogging} it has
L{MemoryLogger.validate} registered as a test cleanup.
"""
MESSAGE = MessageType("mymessage", [], "A message")
class MyTest(TestCase):
@self.validate(None)
def runTest(self, logger):
self.logger = logger
logger.write({"message_type": "wrongmessage"}, MESSAGE._serializer)
test = MyTest()
with self.assertRaises(ValidationError) as context:
test.debug()
# Some reference to the reason:
self.assertIn("wrongmessage", str(context.exception))
# Some reference to which file caused the problem:
self.assertIn("test_testing.py", str(context.exception))
def test_addCleanupTracebacks(self):
"""
When a test method is decorated with L{validateLogging} it has has a
check unflushed tracebacks in the L{MemoryLogger} registered as a
test cleanup.
"""
class MyTest(TestCase):
@self.validate(None)
def runTest(self, logger):
try:
1 / 0
except ZeroDivisionError:
write_traceback(logger)
test = MyTest()
self.assertRaises(UnflushedTracebacks, test.debug)
def test_assertion(self):
"""
If a callable is passed to L{validateLogging}, it is called with the
L{TestCase} instance and the L{MemoryLogger} passed to the test
method.
"""
result = []
class MyTest(TestCase):
def assertLogging(self, logger):
result.append((self, logger))
@self.validate(assertLogging)
def runTest(self, logger):
self.logger = logger
test = MyTest()
test.run()
self.assertEqual(result, [(test, test.logger)])
def test_assertionArguments(self):
"""
If a callable together with additional arguments and keyword arguments are
passed to L{validateLogging}, the callable is called with the additional
args and kwargs.
"""
result = []
class MyTest(TestCase):
def assertLogging(self, logger, x, y):
result.append((self, logger, x, y))
@self.validate(assertLogging, 1, y=2)
def runTest(self, logger):
self.logger = logger
test = MyTest()
test.run()
self.assertEqual(result, [(test, test.logger, 1, 2)])
def test_assertionAfterTest(self):
"""
If a callable is passed to L{validateLogging}, it is called with the
after the main test code has run, allowing it to make assertions
about log messages from the test.
"""
class MyTest(TestCase):
def assertLogging(self, logger):
self.result.append(2)
@self.validate(assertLogging)
def runTest(self, logger):
self.result = [1]
test = MyTest()
test.run()
self.assertEqual(test.result, [1, 2])
def test_assertionBeforeTracebackCleanup(self):
"""
If a callable is passed to L{validateLogging}, it is called with the
before the check for unflushed tracebacks, allowing it to flush
traceback log messages.
"""
class MyTest(TestCase):
def assertLogging(self, logger):
logger.flushTracebacks(ZeroDivisionError)
self.flushed = True
@self.validate(assertLogging)
def runTest(self, logger):
self.flushed = False
try:
1 / 0
except ZeroDivisionError:
write_traceback(logger)
test = MyTest()
test.run()
self.assertTrue(test.flushed)
class ValidateLoggingTests(ValidateLoggingTestsMixin, TestCase):
"""
Tests for L{validate_logging}.
"""
validate = staticmethod(validate_logging)
class CaptureLoggingTests(ValidateLoggingTestsMixin, TestCase):
"""
Tests for L{capture_logging}.
"""
validate = staticmethod(capture_logging)
def setUp(self):
# Since we're not always calling the test method via the TestCase
# infrastructure, sometimes cleanup methods are not called. This
# means the original default logger is not restored. So we do so
# manually. If the issue is a bug in capture_logging itself the
# tests below will catch that.
original_logger = _output._DEFAULT_LOGGER
def cleanup():
_output._DEFAULT_LOGGER = original_logger
self.addCleanup(cleanup)
def test_default_logger(self):
"""
L{capture_logging} captures messages from logging that
doesn't specify a L{Logger}.
"""
class MyTest(TestCase):
@capture_logging(None)
def runTest(self, logger):
Message.log(some_key=1234)
self.logger = logger
test = MyTest()
test.run()
self.assertEqual(test.logger.messages[0]["some_key"], 1234)
def test_global_cleanup(self):
"""
After the function wrapped with L{capture_logging} finishes,
logging that doesn't specify a logger is logged normally.
"""
class MyTest(TestCase):
@capture_logging(None)
def runTest(self, logger):
pass
test = MyTest()
test.run()
messages = []
add_destination(messages.append)
self.addCleanup(remove_destination, messages.append)
Message.log(some_key=1234)
self.assertEqual(messages[0]["some_key"], 1234)
def test_global_cleanup_exception(self):
"""
If the function wrapped with L{capture_logging} throws an exception,
logging that doesn't specify a logger is logged normally.
"""
class MyTest(TestCase):
@capture_logging(None)
def runTest(self, logger):
raise RuntimeError()
test = MyTest()
test.run()
messages = []
add_destination(messages.append)
self.addCleanup(remove_destination, messages.append)
Message.log(some_key=1234)
self.assertEqual(messages[0]["some_key"], 1234)
def test_validationNotRunForSkip(self):
"""
If the decorated test raises L{SkipTest} then the logging validation is
also skipped.
"""
class MyTest(TestCase):
recorded = False
def record(self, logger):
self.recorded = True
@validateLogging(record)
def runTest(self, logger):
raise SkipTest("Do not run this test.")
test = MyTest()
result = TestResult()
test.run(result)
# Verify that the validation function did not run and that the test was
# nevertheless marked as a skip with the correct reason.
self.assertEqual(
(test.recorded, result.skipped, result.errors, result.failures),
(False, [(test, "Do not run this test.")], [], []),
)
class JSONEncodingTests(TestCase):
"""Tests for L{capture_logging} JSON encoder support."""
@skipUnless(np, "NumPy is not installed.")
@capture_logging(None)
def test_default_JSON_encoder(self, logger):
"""
L{capture_logging} validates using L{EliotJSONEncoder} by default.
"""
# Default JSON encoder can't handle NumPy:
log_message(message_type="hello", number=np.uint32(12))
@capture_logging(None, encoder_=CustomJSONEncoder)
def test_custom_JSON_encoder(self, logger):
"""
L{capture_logging} can be called with a custom JSON encoder, which is then
used for validation.
"""
# Default JSON encoder can't handle this custom object:
log_message(message_type="hello", object=CustomObject())
MESSAGE1 = MessageType(
"message1", [Field.forTypes("x", [int], "A number")], "A message for testing."
)
MESSAGE2 = MessageType("message2", [], "A message for testing.")
class AssertHasMessageTests(TestCase):
"""
Tests for L{assertHasMessage}.
"""
class UnitTest(TestCase):
"""
Test case that can be instantiated.
"""
def runTest(self):
pass
def test_failIfNoMessagesOfType(self):
"""
L{assertHasMessage} raises L{AssertionError} if the given L{MemoryLogger}
has no messages of the given L{MessageType}.
"""
test = self.UnitTest()
logger = MemoryLogger()
MESSAGE1(x=123).write(logger)
self.assertRaises(AssertionError, assertHasMessage, test, logger, MESSAGE2)
def test_returnsIfMessagesOfType(self):
"""
L{assertHasMessage} returns the first message of the given L{MessageType}.
"""
test = self.UnitTest()
logger = MemoryLogger()
MESSAGE1(x=123).write(logger)
self.assertEqual(
assertHasMessage(test, logger, MESSAGE1),
LoggedMessage.ofType(logger.messages, MESSAGE1)[0],
)
def test_failIfNotSubset(self):
"""
L{assertHasMessage} raises L{AssertionError} if the found message doesn't
contain the given fields.
"""
test = self.UnitTest()
logger = MemoryLogger()
MESSAGE1(x=123).write(logger)
self.assertRaises(
AssertionError, assertHasMessage, test, logger, MESSAGE1, {"x": 24}
)
def test_returnsIfSubset(self):
"""
L{assertHasMessage} returns the first message of the given L{MessageType} if
it contains the given fields.
"""
test = self.UnitTest()
logger = MemoryLogger()
MESSAGE1(x=123).write(logger)
self.assertEqual(
assertHasMessage(test, logger, MESSAGE1, {"x": 123}),
LoggedMessage.ofType(logger.messages, MESSAGE1)[0],
)
ACTION1 = ActionType(
"action1",
[Field.forTypes("x", [int], "A number")],
[Field.forTypes("result", [int], "A number")],
"A action for testing.",
)
ACTION2 = ActionType("action2", [], [], "A action for testing.")
class AssertHasActionTests(TestCase):
"""
Tests for L{assertHasAction}.
"""
class UnitTest(TestCase):
"""
Test case that can be instantiated.
"""
def runTest(self):
pass
def test_failIfNoActionsOfType(self):
"""
L{assertHasAction} raises L{AssertionError} if the given L{MemoryLogger}
has no actions of the given L{ActionType}.
"""
test = self.UnitTest()
logger = MemoryLogger()
with ACTION1(logger, x=123):
pass
self.assertRaises(AssertionError, assertHasAction, test, logger, ACTION2, True)
def test_failIfWrongSuccessStatus(self):
"""
L{assertHasAction} raises L{AssertionError} if the given success status does
not match that of the found actions.
"""
test = self.UnitTest()
logger = MemoryLogger()
with ACTION1(logger, x=123):
pass
try:
with ACTION2(logger):
1 / 0
except ZeroDivisionError:
pass
self.assertRaises(AssertionError, assertHasAction, test, logger, ACTION1, False)
self.assertRaises(AssertionError, assertHasAction, test, logger, ACTION2, True)
def test_returnsIfMessagesOfType(self):
"""
A successful L{assertHasAction} returns the first message of the given
L{ActionType}.
"""
test = self.UnitTest()
logger = MemoryLogger()
with ACTION1(logger, x=123):
pass
self.assertEqual(
assertHasAction(test, logger, ACTION1, True),
LoggedAction.ofType(logger.messages, ACTION1)[0],
)
def test_failIfNotStartSubset(self):
"""
L{assertHasAction} raises L{AssertionError} if the found action doesn't
contain the given start fields.
"""
test = self.UnitTest()
logger = MemoryLogger()
with ACTION1(logger, x=123):
pass
self.assertRaises(
AssertionError, assertHasAction, test, logger, ACTION1, True, {"x": 24}
)
def test_failIfNotEndSubset(self):
"""
L{assertHasAction} raises L{AssertionError} if the found action doesn't
contain the given end fields.
"""
test = self.UnitTest()
logger = MemoryLogger()
with ACTION1(logger, x=123) as act:
act.addSuccessFields(result=5)
self.assertRaises(
AssertionError,
assertHasAction,
test,
logger,
ACTION1,
True,
startFields={"x": 123},
endFields={"result": 24},
)
def test_returns(self):
"""
A successful L{assertHasAction} returns the first message of the given
L{ActionType} after doing all validation.
"""
test = self.UnitTest()
logger = MemoryLogger()
with ACTION1(logger, x=123) as act:
act.addSuccessFields(result=5)
self.assertEqual(
assertHasAction(test, logger, ACTION1, True, {"x": 123}, {"result": 5}),
LoggedAction.ofType(logger.messages, ACTION1)[0],
)
class PEP8Tests(TestCase):
"""
Tests for PEP 8 method compatibility.
"""
def test_LoggedAction_from_messages(self):
"""
L{LoggedAction.from_messages} is the same as
L{LoggedAction.fromMessages}.
"""
self.assertEqual(LoggedAction.from_messages, LoggedAction.fromMessages)
def test_LoggedAction_of_type(self):
"""
L{LoggedAction.of_type} is the same as
L{LoggedAction.ofType}.
"""
self.assertEqual(LoggedAction.of_type, LoggedAction.ofType)
def test_LoggedAction_end_message(self):
"""
L{LoggedAction.end_message} is the same as L{LoggedAction.endMessage}.
"""
action = LoggedAction({1: 2}, {3: 4}, [])
self.assertEqual(action.end_message, action.endMessage)
def test_LoggedAction_start_message(self):
"""
L{LoggedAction.start_message} is the same as
L{LoggedAction.startMessage}.
"""
action = LoggedAction({1: 2}, {3: 4}, [])
self.assertEqual(action.start_message, action.startMessage)
def test_LoggedMessage_of_type(self):
"""
L{LoggedMessage.of_type} is the same as
L{LoggedMessage.ofType}.
"""
self.assertEqual(LoggedMessage.of_type, LoggedMessage.ofType)
def test_validate_logging(self):
"""
L{validate_logging} is the same as L{validateLogging}.
"""
self.assertEqual(validate_logging, validateLogging)
class LowLevelTestingHooks(TestCase):
"""Tests for lower-level APIs for setting up MemoryLogger."""
@capture_logging(None)
def test_swap_logger(self, logger):
"""C{swap_logger} swaps out the current logger."""
new_logger = MemoryLogger()
old_logger = swap_logger(new_logger)
Message.log(message_type="hello")
# We swapped out old logger for new:
self.assertIs(old_logger, logger)
self.assertEqual(new_logger.messages[0]["message_type"], "hello")
# Now restore old logger:
intermediate_logger = swap_logger(old_logger)
Message.log(message_type="goodbye")
self.assertIs(intermediate_logger, new_logger)
self.assertEqual(logger.messages[0]["message_type"], "goodbye")
def test_check_for_errors_unflushed_tracebacks(self):
"""C{check_for_errors} raises on unflushed tracebacks."""
logger = MemoryLogger()
# No errors initially:
check_for_errors(logger)
try:
1 / 0
except ZeroDivisionError:
write_traceback(logger)
logger.flush_tracebacks(ZeroDivisionError)
# Flushed tracebacks don't count:
check_for_errors(logger)
# But unflushed tracebacks do:
try:
raise RuntimeError
except RuntimeError:
write_traceback(logger)
with self.assertRaises(UnflushedTracebacks):
check_for_errors(logger)
def test_check_for_errors_validation(self):
"""C{check_for_errors} raises on validation errors."""
logger = MemoryLogger()
logger.write({"x": 1, "message_type": "mem"})
# No errors:
check_for_errors(logger)
# Now long something unserializable to JSON:
logger.write({"message_type": object()})
with self.assertRaises(TypeError):
check_for_errors(logger)
|