/usr/lib/python3/dist-packages/twisted/trial/test/test_assertions.py is in python3-twisted-experimental 13.2.0-0ubuntu1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
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 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 | # Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Tests for assertions provided by C{SynchronousTestCase} and C{TestCase},
provided by L{twisted.trial.unittest}.
L{TestFailureTests} demonstrates that L{SynchronousTestCase.fail} works, so that
is the only method on C{twisted.trial.unittest.SynchronousTestCase} that is
initially assumed to work. The test classes are arranged so that the methods
demonstrated to work earlier in the file are used by those later in the file
(even though the runner will probably not run the tests in this order).
"""
from __future__ import division, absolute_import
import warnings
from pprint import pformat
import unittest as pyunit
from twisted.python.util import FancyEqMixin
from twisted.python._reflectpy3 import prefixedMethods, accumulateMethods
from twisted.python.deprecate import deprecated
from twisted.python.versions import Version, getVersionString
from twisted.python.failure import Failure
from twisted.trial import unittest
from twisted.internet.defer import Deferred, fail, succeed
class MockEquality(FancyEqMixin, object):
compareAttributes = ("name",)
def __init__(self, name):
self.name = name
def __repr__(self):
return "MockEquality(%s)" % (self.name,)
class ComparisonError(object):
"""
An object which raises exceptions from its comparison methods.
"""
def _error(self, other):
raise ValueError("Comparison is broken")
__eq__ = __ne__ = _error
class TestFailureTests(pyunit.TestCase):
"""
Tests for the most basic functionality of L{SynchronousTestCase}, for
failing tests.
This class contains tests to demonstrate that L{SynchronousTestCase.fail}
can be used to fail a test, and that that failure is reflected in the test
result object. This should be sufficient functionality so that further
tests can be built on L{SynchronousTestCase} instead of
L{unittest.TestCase}. This depends on L{unittest.TestCase} working.
"""
class FailingTest(unittest.SynchronousTestCase):
def test_fails(self):
self.fail("This test fails.")
def setUp(self):
"""
Load a suite of one test which can be used to exercise the failure
handling behavior.
"""
components = [
__name__, self.__class__.__name__, self.FailingTest.__name__]
self.loader = pyunit.TestLoader()
self.suite = self.loader.loadTestsFromName(".".join(components))
self.test = list(self.suite)[0]
def test_fail(self):
"""
L{SynchronousTestCase.fail} raises
L{SynchronousTestCase.failureException} with the given argument.
"""
try:
self.test.fail("failed")
except self.test.failureException as result:
self.assertEqual("failed", str(result))
else:
self.fail(
"SynchronousTestCase.fail method did not raise "
"SynchronousTestCase.failureException")
def test_failingExceptionFails(self):
"""
When a test method raises L{SynchronousTestCase.failureException}, the test is
marked as having failed on the L{TestResult}.
"""
result = pyunit.TestResult()
self.suite.run(result)
self.failIf(result.wasSuccessful())
self.assertEqual(result.errors, [])
self.assertEqual(len(result.failures), 1)
self.assertEqual(result.failures[0][0], self.test)
class AssertFalseTests(unittest.SynchronousTestCase):
"""
Tests for L{SynchronousTestCase}'s C{assertFalse} and C{failIf} assertion
methods.
This is pretty paranoid. Still, a certain paranoia is healthy if you
are testing a unit testing framework.
@note: As of 11.2, C{assertFalse} is preferred over C{failIf}.
"""
def _assertFalseFalse(self, method):
"""
Perform the positive case test for C{failIf} or C{assertFalse}.
@param method: The test method to test.
"""
for notTrue in [0, 0.0, False, None, (), []]:
result = method(notTrue, "failed on %r" % (notTrue,))
if result != notTrue:
self.fail("Did not return argument %r" % (notTrue,))
def _assertFalseTrue(self, method):
"""
Perform the negative case test for C{failIf} or C{assertFalse}.
@param method: The test method to test.
"""
for true in [1, True, 'cat', [1,2], (3,4)]:
try:
method(true, "failed on %r" % (true,))
except self.failureException as e:
if str(e) != "failed on %r" % (true,):
self.fail("Raised incorrect exception on %r: %r" % (true, e))
else:
self.fail("Call to failIf(%r) didn't fail" % (true,))
def test_failIfFalse(self):
"""
L{SynchronousTestCase.failIf} returns its argument if its argument is
not considered true.
"""
self._assertFalseFalse(self.failIf)
def test_assertFalseFalse(self):
"""
L{SynchronousTestCase.assertFalse} returns its argument if its argument
is not considered true.
"""
self._assertFalseFalse(self.assertFalse)
def test_failIfTrue(self):
"""
L{SynchronousTestCase.failIf} raises
L{SynchronousTestCase.failureException} if its argument is considered
true.
"""
self._assertFalseTrue(self.failIf)
def test_assertFalseTrue(self):
"""
L{SynchronousTestCase.assertFalse} raises
L{SynchronousTestCase.failureException} if its argument is considered
true.
"""
self._assertFalseTrue(self.assertFalse)
class AssertTrueTests(unittest.SynchronousTestCase):
"""
Tests for L{SynchronousTestCase}'s C{assertTrue} and C{failUnless} assertion
methods.
This is pretty paranoid. Still, a certain paranoia is healthy if you
are testing a unit testing framework.
@note: As of 11.2, C{assertTrue} is preferred over C{failUnless}.
"""
def _assertTrueFalse(self, method):
"""
Perform the negative case test for C{assertTrue} and C{failUnless}.
@param method: The test method to test.
"""
for notTrue in [0, 0.0, False, None, (), []]:
try:
method(notTrue, "failed on %r" % (notTrue,))
except self.failureException as e:
if str(e) != "failed on %r" % (notTrue,):
self.fail(
"Raised incorrect exception on %r: %r" % (notTrue, e))
else:
self.fail(
"Call to %s(%r) didn't fail" % (method.__name__, notTrue,))
def _assertTrueTrue(self, method):
"""
Perform the positive case test for C{assertTrue} and C{failUnless}.
@param method: The test method to test.
"""
for true in [1, True, 'cat', [1,2], (3,4)]:
result = method(true, "failed on %r" % (true,))
if result != true:
self.fail("Did not return argument %r" % (true,))
def test_assertTrueFalse(self):
"""
L{SynchronousTestCase.assertTrue} raises
L{SynchronousTestCase.failureException} if its argument is not
considered true.
"""
self._assertTrueFalse(self.assertTrue)
def test_failUnlessFalse(self):
"""
L{SynchronousTestCase.failUnless} raises
L{SynchronousTestCase.failureException} if its argument is not
considered true.
"""
self._assertTrueFalse(self.failUnless)
def test_assertTrueTrue(self):
"""
L{SynchronousTestCase.assertTrue} returns its argument if its argument
is considered true.
"""
self._assertTrueTrue(self.assertTrue)
def test_failUnlessTrue(self):
"""
L{SynchronousTestCase.failUnless} returns its argument if its argument
is considered true.
"""
self._assertTrueTrue(self.failUnless)
class TestSynchronousAssertions(unittest.SynchronousTestCase):
"""
Tests for L{SynchronousTestCase}'s assertion methods. That is, failUnless*,
failIf*, assert* (not covered by other more specific test classes).
Note: As of 11.2, assertEqual is preferred over the failUnlessEqual(s)
variants. Tests have been modified to reflect this preference.
This is pretty paranoid. Still, a certain paranoia is healthy if you are
testing a unit testing framework.
"""
def _testEqualPair(self, first, second):
x = self.assertEqual(first, second)
if x != first:
self.fail("assertEqual should return first parameter")
def _testUnequalPair(self, first, second):
try:
self.assertEqual(first, second)
except self.failureException as e:
expected = 'not equal:\na = %s\nb = %s\n' % (
pformat(first), pformat(second))
if str(e) != expected:
self.fail("Expected: %r; Got: %s" % (expected, str(e)))
else:
self.fail("Call to assertEqual(%r, %r) didn't fail"
% (first, second))
def test_assertEqual_basic(self):
self._testEqualPair('cat', 'cat')
self._testUnequalPair('cat', 'dog')
self._testEqualPair([1], [1])
self._testUnequalPair([1], 'orange')
def test_assertEqual_custom(self):
x = MockEquality('first')
y = MockEquality('second')
z = MockEquality('first')
self._testEqualPair(x, x)
self._testEqualPair(x, z)
self._testUnequalPair(x, y)
self._testUnequalPair(y, z)
def test_assertEqualMessage(self):
"""
When a message is passed to L{assertEqual}, it is included in the
error message.
"""
exception = self.assertRaises(
self.failureException, self.assertEqual,
'foo', 'bar', 'message')
self.assertEqual(
str(exception),
"message\nnot equal:\na = 'foo'\nb = 'bar'\n")
def test_assertEqualNoneMessage(self):
"""
If a message is specified as C{None}, it is not included in the error
message of L{assertEqual}.
"""
exception = self.assertRaises(
self.failureException, self.assertEqual, 'foo', 'bar', None)
self.assertEqual(str(exception), "not equal:\na = 'foo'\nb = 'bar'\n")
def test_assertEqual_incomparable(self):
apple = ComparisonError()
orange = ["orange"]
try:
self.assertEqual(apple, orange)
except self.failureException:
self.fail("Fail raised when ValueError ought to have been raised.")
except ValueError:
# good. error not swallowed
pass
else:
self.fail("Comparing %r and %r should have raised an exception"
% (apple, orange))
def _raiseError(self, error):
raise error
def test_failUnlessRaises_expected(self):
x = self.failUnlessRaises(ValueError, self._raiseError, ValueError)
self.failUnless(isinstance(x, ValueError),
"Expect failUnlessRaises to return instance of raised "
"exception.")
def test_failUnlessRaises_unexpected(self):
try:
self.failUnlessRaises(ValueError, self._raiseError, TypeError)
except TypeError:
self.fail("failUnlessRaises shouldn't re-raise unexpected "
"exceptions")
except self.failureException:
# what we expect
pass
else:
self.fail("Expected exception wasn't raised. Should have failed")
def test_failUnlessRaises_noException(self):
try:
self.failUnlessRaises(ValueError, lambda : None)
except self.failureException as e:
self.assertEqual(str(e),
'ValueError not raised (None returned)')
else:
self.fail("Exception not raised. Should have failed")
def test_failUnlessRaises_failureException(self):
x = self.failUnlessRaises(self.failureException, self._raiseError,
self.failureException)
self.failUnless(isinstance(x, self.failureException),
"Expected %r instance to be returned"
% (self.failureException,))
try:
x = self.failUnlessRaises(self.failureException, self._raiseError,
ValueError)
except self.failureException:
# what we expect
pass
else:
self.fail("Should have raised exception")
def test_failIfEqual_basic(self):
x, y, z = [1], [2], [1]
ret = self.failIfEqual(x, y)
self.assertEqual(ret, x,
"failIfEqual should return first parameter")
self.failUnlessRaises(self.failureException,
self.failIfEqual, x, x)
self.failUnlessRaises(self.failureException,
self.failIfEqual, x, z)
def test_failIfEqual_customEq(self):
x = MockEquality('first')
y = MockEquality('second')
z = MockEquality('fecund')
ret = self.failIfEqual(x, y)
self.assertEqual(ret, x,
"failIfEqual should return first parameter")
self.failUnlessRaises(self.failureException,
self.failIfEqual, x, x)
self.failIfEqual(x, z, "__ne__ should make these not equal")
def test_failIfIdenticalPositive(self):
"""
C{failIfIdentical} returns its first argument if its first and second
arguments are not the same object.
"""
x = object()
y = object()
result = self.failIfIdentical(x, y)
self.assertEqual(x, result)
def test_failIfIdenticalNegative(self):
"""
C{failIfIdentical} raises C{failureException} if its first and second
arguments are the same object.
"""
x = object()
self.failUnlessRaises(self.failureException,
self.failIfIdentical, x, x)
def test_failUnlessIdentical(self):
x, y, z = [1], [1], [2]
ret = self.failUnlessIdentical(x, x)
self.assertEqual(ret, x,
'failUnlessIdentical should return first '
'parameter')
self.failUnlessRaises(self.failureException,
self.failUnlessIdentical, x, y)
self.failUnlessRaises(self.failureException,
self.failUnlessIdentical, x, z)
def test_failUnlessApproximates(self):
x, y, z = 1.0, 1.1, 1.2
self.failUnlessApproximates(x, x, 0.2)
ret = self.failUnlessApproximates(x, y, 0.2)
self.assertEqual(ret, x, "failUnlessApproximates should return "
"first parameter")
self.failUnlessRaises(self.failureException,
self.failUnlessApproximates, x, z, 0.1)
self.failUnlessRaises(self.failureException,
self.failUnlessApproximates, x, y, 0.1)
def test_failUnlessAlmostEqual(self):
precision = 5
x = 8.000001
y = 8.00001
z = 8.000002
self.failUnlessAlmostEqual(x, x, precision)
ret = self.failUnlessAlmostEqual(x, z, precision)
self.assertEqual(ret, x, "failUnlessAlmostEqual should return "
"first parameter (%r, %r)" % (ret, x))
self.failUnlessRaises(self.failureException,
self.failUnlessAlmostEqual, x, y, precision)
def test_failIfAlmostEqual(self):
precision = 5
x = 8.000001
y = 8.00001
z = 8.000002
ret = self.failIfAlmostEqual(x, y, precision)
self.assertEqual(ret, x, "failIfAlmostEqual should return "
"first parameter (%r, %r)" % (ret, x))
self.failUnlessRaises(self.failureException,
self.failIfAlmostEqual, x, x, precision)
self.failUnlessRaises(self.failureException,
self.failIfAlmostEqual, x, z, precision)
def test_failUnlessSubstring(self):
x = "cat"
y = "the dog sat"
z = "the cat sat"
self.failUnlessSubstring(x, x)
ret = self.failUnlessSubstring(x, z)
self.assertEqual(ret, x, 'should return first parameter')
self.failUnlessRaises(self.failureException,
self.failUnlessSubstring, x, y)
self.failUnlessRaises(self.failureException,
self.failUnlessSubstring, z, x)
def test_failIfSubstring(self):
x = "cat"
y = "the dog sat"
z = "the cat sat"
self.failIfSubstring(z, x)
ret = self.failIfSubstring(x, y)
self.assertEqual(ret, x, 'should return first parameter')
self.failUnlessRaises(self.failureException,
self.failIfSubstring, x, x)
self.failUnlessRaises(self.failureException,
self.failIfSubstring, x, z)
def test_assertIs(self):
"""
L{assertIs} passes if two objects are identical.
"""
a = MockEquality("first")
self.assertIs(a, a)
def test_assertIsError(self):
"""
L{assertIs} fails if two objects are not identical.
"""
a, b = MockEquality("first"), MockEquality("first")
self.assertEqual(a, b)
self.assertRaises(self.failureException, self.assertIs, a, b)
def test_assertIsNot(self):
"""
L{assertIsNot} passes if two objects are not identical.
"""
a, b = MockEquality("first"), MockEquality("first")
self.assertEqual(a, b)
self.assertIsNot(a, b)
def test_assertIsNotError(self):
"""
L{assertIsNot} fails if two objects are identical.
"""
a = MockEquality("first")
self.assertRaises(self.failureException, self.assertIsNot, a, a)
def test_assertIsInstance(self):
"""
Test a true condition of assertIsInstance.
"""
A = type('A', (object,), {})
a = A()
self.assertIsInstance(a, A)
def test_assertIsInstanceMultipleClasses(self):
"""
Test a true condition of assertIsInstance with multiple classes.
"""
A = type('A', (object,), {})
B = type('B', (object,), {})
a = A()
self.assertIsInstance(a, (A, B))
def test_assertIsInstanceError(self):
"""
Test an error with assertIsInstance.
"""
A = type('A', (object,), {})
B = type('B', (object,), {})
a = A()
self.assertRaises(self.failureException, self.assertIsInstance, a, B)
def test_assertIsInstanceErrorMultipleClasses(self):
"""
Test an error with assertIsInstance and multiple classes.
"""
A = type('A', (object,), {})
B = type('B', (object,), {})
C = type('C', (object,), {})
a = A()
self.assertRaises(self.failureException, self.assertIsInstance, a, (B, C))
def test_assertIsInstanceCustomMessage(self):
"""
If L{TestCase.assertIsInstance} is passed a custom message as its 3rd
argument, the message is included in the failure exception raised when
the assertion fails.
"""
exc = self.assertRaises(
self.failureException,
self.assertIsInstance, 3, str, "Silly assertion")
self.assertIn("Silly assertion", str(exc))
def test_assertNotIsInstance(self):
"""
Test a true condition of assertNotIsInstance.
"""
A = type('A', (object,), {})
B = type('B', (object,), {})
a = A()
self.assertNotIsInstance(a, B)
def test_assertNotIsInstanceMultipleClasses(self):
"""
Test a true condition of assertNotIsInstance and multiple classes.
"""
A = type('A', (object,), {})
B = type('B', (object,), {})
C = type('C', (object,), {})
a = A()
self.assertNotIsInstance(a, (B, C))
def test_assertNotIsInstanceError(self):
"""
Test an error with assertNotIsInstance.
"""
A = type('A', (object,), {})
a = A()
error = self.assertRaises(self.failureException,
self.assertNotIsInstance, a, A)
self.assertEqual(str(error), "%r is an instance of %s" % (a, A))
def test_assertNotIsInstanceErrorMultipleClasses(self):
"""
Test an error with assertNotIsInstance and multiple classes.
"""
A = type('A', (object,), {})
B = type('B', (object,), {})
a = A()
self.assertRaises(self.failureException, self.assertNotIsInstance, a, (A, B))
def test_assertDictEqual(self):
"""
L{twisted.trial.unittest.TestCase} supports the C{assertDictEqual}
method inherited from the standard library in Python 2.7.
"""
self.assertDictEqual({'a': 1}, {'a': 1})
if getattr(unittest.SynchronousTestCase, 'assertDictEqual', None) is None:
test_assertDictEqual.skip = (
"assertDictEqual is not available on this version of Python")
class WarningAssertionTests(unittest.SynchronousTestCase):
def test_assertWarns(self):
"""
Test basic assertWarns report.
"""
def deprecated(a):
warnings.warn("Woo deprecated", category=DeprecationWarning)
return a
r = self.assertWarns(DeprecationWarning, "Woo deprecated", __file__,
deprecated, 123)
self.assertEqual(r, 123)
def test_assertWarnsRegistryClean(self):
"""
Test that assertWarns cleans the warning registry, so the warning is
not swallowed the second time.
"""
def deprecated(a):
warnings.warn("Woo deprecated", category=DeprecationWarning)
return a
r1 = self.assertWarns(DeprecationWarning, "Woo deprecated", __file__,
deprecated, 123)
self.assertEqual(r1, 123)
# The warning should be raised again
r2 = self.assertWarns(DeprecationWarning, "Woo deprecated", __file__,
deprecated, 321)
self.assertEqual(r2, 321)
def test_assertWarnsError(self):
"""
Test assertWarns failure when no warning is generated.
"""
def normal(a):
return a
self.assertRaises(self.failureException,
self.assertWarns, DeprecationWarning, "Woo deprecated", __file__,
normal, 123)
def test_assertWarnsWrongCategory(self):
"""
Test assertWarns failure when the category is wrong.
"""
def deprecated(a):
warnings.warn("Foo deprecated", category=DeprecationWarning)
return a
self.assertRaises(self.failureException,
self.assertWarns, UserWarning, "Foo deprecated", __file__,
deprecated, 123)
def test_assertWarnsWrongMessage(self):
"""
Test assertWarns failure when the message is wrong.
"""
def deprecated(a):
warnings.warn("Foo deprecated", category=DeprecationWarning)
return a
self.assertRaises(self.failureException,
self.assertWarns, DeprecationWarning, "Bar deprecated", __file__,
deprecated, 123)
def test_assertWarnsWrongFile(self):
"""
If the warning emitted by a function refers to a different file than is
passed to C{assertWarns}, C{failureException} is raised.
"""
def deprecated(a):
# stacklevel=2 points at the direct caller of the function. The
# way assertRaises is invoked below, the direct caller will be
# something somewhere in trial, not something in this file. In
# Python 2.5 and earlier, stacklevel of 0 resulted in a warning
# pointing to the warnings module itself. Starting in Python 2.6,
# stacklevel of 0 and 1 both result in a warning pointing to *this*
# file, presumably due to the fact that the warn function is
# implemented in C and has no convenient Python
# filename/linenumber.
warnings.warn(
"Foo deprecated", category=DeprecationWarning, stacklevel=2)
self.assertRaises(
self.failureException,
# Since the direct caller isn't in this file, try to assert that
# the warning *does* point to this file, so that assertWarns raises
# an exception.
self.assertWarns, DeprecationWarning, "Foo deprecated", __file__,
deprecated, 123)
def test_assertWarnsOnClass(self):
"""
Test assertWarns works when creating a class instance.
"""
class Warn:
def __init__(self):
warnings.warn("Do not call me", category=RuntimeWarning)
r = self.assertWarns(RuntimeWarning, "Do not call me", __file__,
Warn)
self.assertTrue(isinstance(r, Warn))
r = self.assertWarns(RuntimeWarning, "Do not call me", __file__,
Warn)
self.assertTrue(isinstance(r, Warn))
def test_assertWarnsOnMethod(self):
"""
Test assertWarns works when used on an instance method.
"""
class Warn:
def deprecated(self, a):
warnings.warn("Bar deprecated", category=DeprecationWarning)
return a
w = Warn()
r = self.assertWarns(DeprecationWarning, "Bar deprecated", __file__,
w.deprecated, 321)
self.assertEqual(r, 321)
r = self.assertWarns(DeprecationWarning, "Bar deprecated", __file__,
w.deprecated, 321)
self.assertEqual(r, 321)
def test_assertWarnsOnCall(self):
"""
Test assertWarns works on instance with C{__call__} method.
"""
class Warn:
def __call__(self, a):
warnings.warn("Egg deprecated", category=DeprecationWarning)
return a
w = Warn()
r = self.assertWarns(DeprecationWarning, "Egg deprecated", __file__,
w, 321)
self.assertEqual(r, 321)
r = self.assertWarns(DeprecationWarning, "Egg deprecated", __file__,
w, 321)
self.assertEqual(r, 321)
def test_assertWarnsFilter(self):
"""
Test assertWarns on a warning filterd by default.
"""
def deprecated(a):
warnings.warn("Woo deprecated", category=PendingDeprecationWarning)
return a
r = self.assertWarns(PendingDeprecationWarning, "Woo deprecated",
__file__, deprecated, 123)
self.assertEqual(r, 123)
def test_assertWarnsMultipleWarnings(self):
"""
C{assertWarns} does not raise an exception if the function it is passed
triggers the same warning more than once.
"""
def deprecated():
warnings.warn("Woo deprecated", category=PendingDeprecationWarning)
def f():
deprecated()
deprecated()
self.assertWarns(
PendingDeprecationWarning, "Woo deprecated", __file__, f)
def test_assertWarnsDifferentWarnings(self):
"""
For now, assertWarns is unable to handle multiple different warnings,
so it should raise an exception if it's the case.
"""
def deprecated(a):
warnings.warn("Woo deprecated", category=DeprecationWarning)
warnings.warn("Another one", category=PendingDeprecationWarning)
e = self.assertRaises(self.failureException,
self.assertWarns, DeprecationWarning, "Woo deprecated",
__file__, deprecated, 123)
self.assertEqual(str(e), "Can't handle different warnings")
def test_assertWarnsAfterUnassertedWarning(self):
"""
Warnings emitted before L{TestCase.assertWarns} is called do not get
flushed and do not alter the behavior of L{TestCase.assertWarns}.
"""
class TheWarning(Warning):
pass
def f(message):
warnings.warn(message, category=TheWarning)
f("foo")
self.assertWarns(TheWarning, "bar", __file__, f, "bar")
[warning] = self.flushWarnings([f])
self.assertEqual(warning['message'], "foo")
class TestResultOfAssertions(unittest.SynchronousTestCase):
"""
Tests for L{SynchronousTestCase.successResultOf},
L{SynchronousTestCase.failureResultOf}, and
L{SynchronousTestCase.assertNoResult}.
"""
result = object()
failure = Failure(Exception("Bad times"))
def test_withoutSuccessResult(self):
"""
L{SynchronousTestCase.successResultOf} raises
L{SynchronousTestCase.failureException} when called with a L{Deferred}
with no current result.
"""
self.assertRaises(
self.failureException, self.successResultOf, Deferred())
def test_successResultOfWithFailure(self):
"""
L{SynchronousTestCase.successResultOf} raises
L{SynchronousTestCase.failureException} when called with a L{Deferred}
with a failure result.
"""
self.assertRaises(
self.failureException, self.successResultOf, fail(self.failure))
def test_successResultOfWithFailureHasTraceback(self):
"""
L{SynchronousTestCase.successResultOf} raises a
L{SynchronousTestCase.failureException} that has the original failure
traceback when called with a L{Deferred} with a failure result.
"""
try:
self.successResultOf(fail(self.failure))
except self.failureException as e:
self.assertIn(self.failure.getTraceback(), str(e))
def test_withoutFailureResult(self):
"""
L{SynchronousTestCase.failureResultOf} raises
L{SynchronousTestCase.failureException} when called with a L{Deferred}
with no current result.
"""
self.assertRaises(
self.failureException, self.failureResultOf, Deferred())
def test_failureResultOfWithSuccess(self):
"""
L{SynchronousTestCase.failureResultOf} raises
L{SynchronousTestCase.failureException} when called with a L{Deferred}
with a success result.
"""
self.assertRaises(
self.failureException, self.failureResultOf, succeed(self.result))
def test_failureResultOfWithWrongFailure(self):
"""
L{SynchronousTestCase.failureResultOf} raises
L{SynchronousTestCase.failureException} when called with a L{Deferred}
with a failure type that was not expected.
"""
self.assertRaises(
self.failureException, self.failureResultOf, fail(self.failure),
KeyError)
def test_failureResultOfWithWrongFailureOneExpectedFailure(self):
"""
L{SynchronousTestCase.failureResultOf} raises
L{SynchronousTestCase.failureException} when called with a L{Deferred}
with a failure type that was not expected, and the
L{SynchronousTestCase.failureException} message contains the original
failure traceback as well as the expected failure type
"""
try:
self.failureResultOf(fail(self.failure), KeyError)
except self.failureException as e:
self.assertIn(self.failure.getTraceback(), str(e))
self.assertIn(
"Failure of type ({0}.{1}) expected on".format(
KeyError.__module__, KeyError.__name__),
str(e))
def test_failureResultOfWithWrongFailureMultiExpectedFailure(self):
"""
L{SynchronousTestCase.failureResultOf} raises
L{SynchronousTestCase.failureException} when called with a L{Deferred}
with a failure type that was not expected, and the
L{SynchronousTestCase.failureException} message contains the original
failure traceback as well as the expected failure types in the error
message
"""
try:
self.failureResultOf(fail(self.failure), KeyError, IOError)
except self.failureException as e:
self.assertIn(self.failure.getTraceback(), str(e))
self.assertIn(
"Failure of type ({0}.{1} or {2}.{3}) expected on".format(
KeyError.__module__, KeyError.__name__,
IOError.__module__, IOError.__name__),
str(e))
def test_withSuccessResult(self):
"""
When passed a L{Deferred} which currently has a result (ie,
L{Deferred.addCallback} would cause the added callback to be called
before C{addCallback} returns), L{SynchronousTestCase.successResultOf}
returns that result.
"""
self.assertIdentical(
self.result, self.successResultOf(succeed(self.result)))
def test_withExpectedFailureResult(self):
"""
When passed a L{Deferred} which currently has a L{Failure} result (ie,
L{Deferred.addErrback} would cause the added errback to be called
before C{addErrback} returns), L{SynchronousTestCase.failureResultOf}
returns that L{Failure} if that L{Failure}'s type is expected.
"""
self.assertIdentical(
self.failure,
self.failureResultOf(fail(self.failure), self.failure.type,
KeyError))
def test_withFailureResult(self):
"""
When passed a L{Deferred} which currently has a L{Failure} result
(ie, L{Deferred.addErrback} would cause the added errback to be called
before C{addErrback} returns), L{SynchronousTestCase.failureResultOf}
returns that L{Failure}.
"""
self.assertIdentical(
self.failure, self.failureResultOf(fail(self.failure)))
def test_assertNoResultSuccess(self):
"""
When passed a L{Deferred} which currently has a success result (see
L{test_withSuccessResult}), L{SynchronousTestCase.assertNoResult} raises
L{SynchronousTestCase.failureException}.
"""
self.assertRaises(
self.failureException, self.assertNoResult, succeed(self.result))
def test_assertNoResultFailure(self):
"""
When passed a L{Deferred} which currently has a failure result (see
L{test_withFailureResult}), L{SynchronousTestCase.assertNoResult} raises
L{SynchronousTestCase.failureException}.
"""
self.assertRaises(
self.failureException, self.assertNoResult, fail(self.failure))
def test_assertNoResult(self):
"""
When passed a L{Deferred} with no current result,
"""
self.assertNoResult(Deferred())
def test_assertNoResultPropagatesSuccess(self):
"""
When passed a L{Deferred} with no current result, which is then
fired with a success result, L{SynchronousTestCase.assertNoResult}
doesn't modify the result of the L{Deferred}.
"""
d = Deferred()
self.assertNoResult(d)
d.callback(self.result)
self.assertEqual(self.result, self.successResultOf(d))
def test_assertNoResultPropagatesLaterFailure(self):
"""
When passed a L{Deferred} with no current result, which is then
fired with a L{Failure} result, L{SynchronousTestCase.assertNoResult}
doesn't modify the result of the L{Deferred}.
"""
d = Deferred()
self.assertNoResult(d)
d.errback(self.failure)
self.assertEqual(self.failure, self.failureResultOf(d))
def test_assertNoResultSwallowsImmediateFailure(self):
"""
When passed a L{Deferred} which currently has a L{Failure} result,
L{SynchronousTestCase.assertNoResult} changes the result of the
L{Deferred} to a success.
"""
d = fail(self.failure)
try:
self.assertNoResult(d)
except self.failureException:
pass
self.assertEqual(None, self.successResultOf(d))
class TestAssertionNames(unittest.SynchronousTestCase):
"""
Tests for consistency of naming within TestCase assertion methods
"""
def _getAsserts(self):
dct = {}
accumulateMethods(self, dct, 'assert')
return [ dct[k] for k in dct if not k.startswith('Not') and k != '_' ]
def _name(self, x):
return x.__name__
def test_failUnlessMatchesAssert(self):
"""
The C{failUnless*} test methods are a subset of the C{assert*} test
methods. This is intended to ensure that methods using the
I{failUnless} naming scheme are not added without corresponding methods
using the I{assert} naming scheme. The I{assert} naming scheme is
preferred, and new I{assert}-prefixed methods may be added without
corresponding I{failUnless}-prefixed methods.
"""
asserts = set(self._getAsserts())
failUnlesses = set(prefixedMethods(self, 'failUnless'))
self.assertEqual(
failUnlesses, asserts.intersection(failUnlesses))
def test_failIf_matches_assertNot(self):
asserts = prefixedMethods(unittest.SynchronousTestCase, 'assertNot')
failIfs = prefixedMethods(unittest.SynchronousTestCase, 'failIf')
self.assertEqual(sorted(asserts, key=self._name),
sorted(failIfs, key=self._name))
def test_equalSpelling(self):
for name, value in vars(self).items():
if not callable(value):
continue
if name.endswith('Equal'):
self.failUnless(hasattr(self, name+'s'),
"%s but no %ss" % (name, name))
self.assertEqual(value, getattr(self, name+'s'))
if name.endswith('Equals'):
self.failUnless(hasattr(self, name[:-1]),
"%s but no %s" % (name, name[:-1]))
self.assertEqual(value, getattr(self, name[:-1]))
class TestCallDeprecated(unittest.SynchronousTestCase):
"""
Test use of the L{SynchronousTestCase.callDeprecated} method with version objects.
"""
version = Version('Twisted', 8, 0, 0)
def test_callDeprecatedSuppressesWarning(self):
"""
callDeprecated calls a deprecated callable, suppressing the
deprecation warning.
"""
self.callDeprecated(self.version, oldMethod, 'foo')
self.assertEqual(
self.flushWarnings(), [], "No warnings should be shown")
def test_callDeprecatedCallsFunction(self):
"""
L{callDeprecated} actually calls the callable passed to it, and
forwards the result.
"""
result = self.callDeprecated(self.version, oldMethod, 'foo')
self.assertEqual('foo', result)
def test_failsWithoutDeprecation(self):
"""
L{callDeprecated} raises a test failure if the callable is not
deprecated.
"""
def notDeprecated():
pass
exception = self.assertRaises(
self.failureException,
self.callDeprecated, self.version, notDeprecated)
self.assertEqual(
"%r is not deprecated." % notDeprecated, str(exception))
def test_failsWithIncorrectDeprecation(self):
"""
callDeprecated raises a test failure if the callable was deprecated
at a different version to the one expected.
"""
differentVersion = Version('Foo', 1, 2, 3)
exception = self.assertRaises(
self.failureException,
self.callDeprecated,
differentVersion, oldMethod, 'foo')
self.assertIn(getVersionString(self.version), str(exception))
self.assertIn(getVersionString(differentVersion), str(exception))
def test_nestedDeprecation(self):
"""
L{callDeprecated} ignores all deprecations apart from the first.
Multiple warnings are generated when a deprecated function calls
another deprecated function. The first warning is the one generated by
the explicitly called function. That's the warning that we care about.
"""
differentVersion = Version('Foo', 1, 2, 3)
def nestedDeprecation(*args):
return oldMethod(*args)
nestedDeprecation = deprecated(differentVersion)(nestedDeprecation)
self.callDeprecated(differentVersion, nestedDeprecation, 24)
# The oldMethod deprecation should have been emitted too, not captured
# by callDeprecated. Flush it now to make sure it did happen and to
# prevent it from showing up on stdout.
warningsShown = self.flushWarnings()
self.assertEqual(len(warningsShown), 1)
def test_callDeprecationWithMessage(self):
"""
L{callDeprecated} can take a message argument used to check the warning
emitted.
"""
self.callDeprecated((self.version, "newMethod"),
oldMethodReplaced, 1)
def test_callDeprecationWithWrongMessage(self):
"""
If the message passed to L{callDeprecated} doesn't match,
L{callDeprecated} raises a test failure.
"""
exception = self.assertRaises(
self.failureException,
self.callDeprecated,
(self.version, "something.wrong"),
oldMethodReplaced, 1)
self.assertIn(getVersionString(self.version), str(exception))
self.assertIn("please use newMethod instead", str(exception))
@deprecated(TestCallDeprecated.version)
def oldMethod(x):
"""
Deprecated method for testing.
"""
return x
@deprecated(TestCallDeprecated.version, replacement="newMethod")
def oldMethodReplaced(x):
"""
Another deprecated method, which has been deprecated in favor of the
mythical 'newMethod'.
"""
return 2 * x
|