/usr/lib/python3/dist-packages/plainbox/impl/session/test_resume.py is in python3-plainbox 0.25-1.
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 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 | # This file is part of Checkbox.
#
# Copyright 2012, 2013, 2014 Canonical Ltd.
# Written by:
# Zygmunt Krynicki <zygmunt.krynicki@canonical.com>
#
# Checkbox is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3,
# as published by the Free Software Foundation.
#
# Checkbox is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Checkbox. If not, see <http://www.gnu.org/licenses/>.
"""
:mod:`plainbox.impl.session.test_resume`
========================================
Test definitions for :mod:`plainbox.impl.session.resume` module
"""
from unittest import TestCase
import base64
import binascii
import copy
import gzip
import json
from plainbox.abc import IJobQualifier
from plainbox.abc import IJobResult
from plainbox.impl.job import JobDefinition
from plainbox.impl.resource import Resource
from plainbox.impl.result import DiskJobResult
from plainbox.impl.result import IOLogRecord
from plainbox.impl.result import MemoryJobResult
from plainbox.impl.session.resume import CorruptedSessionError
from plainbox.impl.session.resume import IncompatibleJobError
from plainbox.impl.session.resume import IncompatibleSessionError
from plainbox.impl.session.resume import ResumeDiscardQualifier
from plainbox.impl.session.resume import SessionPeekHelper
from plainbox.impl.session.resume import SessionPeekHelper1
from plainbox.impl.session.resume import SessionPeekHelper2
from plainbox.impl.session.resume import SessionPeekHelper3
from plainbox.impl.session.resume import SessionPeekHelper4
from plainbox.impl.session.resume import SessionPeekHelper5
from plainbox.impl.session.resume import SessionPeekHelper6
from plainbox.impl.session.resume import SessionResumeError
from plainbox.impl.session.resume import SessionResumeHelper
from plainbox.impl.session.resume import SessionResumeHelper1
from plainbox.impl.session.resume import SessionResumeHelper2
from plainbox.impl.session.resume import SessionResumeHelper3
from plainbox.impl.session.resume import SessionResumeHelper4
from plainbox.impl.session.resume import SessionResumeHelper5
from plainbox.impl.session.resume import SessionResumeHelper6
from plainbox.impl.session.state import SessionState
from plainbox.impl.testing_utils import make_job
from plainbox.testing_utils.testcases import TestCaseWithParameters
from plainbox.vendor import mock
class ResumeDiscardQualifierTests(TestCase):
"""
Tests for the ResumeDiscardQualifier class
"""
def setUp(self):
# The initializer accepts a collection of job IDs to retain
self.obj = ResumeDiscardQualifier({'foo', 'bar', 'froz'})
def test_init(self):
self.assertEqual(
self.obj._retain_id_set, frozenset(['foo', 'bar', 'froz']))
def test_get_simple_match(self):
# Direct hits return the IGNORE vote as those jobs are not to be
# removed. Everything else should return VOTE_INCLUDE (include for
# removal)
self.assertEqual(
self.obj.get_vote(JobDefinition({'id': 'foo'})),
IJobQualifier.VOTE_IGNORE)
self.assertEqual(
self.obj.get_vote(JobDefinition({'id': 'bar'})),
IJobQualifier.VOTE_IGNORE)
self.assertEqual(
self.obj.get_vote(JobDefinition({'id': 'froz'})),
IJobQualifier.VOTE_IGNORE)
# Jobs that are in the retain set are NOT designated
self.assertEqual(
self.obj.designates(JobDefinition({'id': 'bar'})), False)
self.assertEqual(
self.obj.designates(JobDefinition({'id': 'foo'})), False)
# Jobs that are not on the retain list are INCLUDED and marked for
# removal. This includes jobs that are substrings of strings in the
# retain set, ids are matched exactly, not by pattern.
self.assertEqual(
self.obj.get_vote(JobDefinition({'id': 'foobar'})),
IJobQualifier.VOTE_INCLUDE)
self.assertEqual(
self.obj.get_vote(JobDefinition({'id': 'fo'})),
IJobQualifier.VOTE_INCLUDE)
class SessionResumeExceptionTests(TestCase):
"""
Tests for the various exceptions defined in the resume module
"""
def test_resume_exception_inheritance(self):
"""
verify that all three exception classes inherit from the common base
"""
self.assertTrue(issubclass(
CorruptedSessionError, SessionResumeError))
self.assertTrue(issubclass(
IncompatibleSessionError, SessionResumeError))
self.assertTrue(issubclass(
IncompatibleJobError, SessionResumeError))
class SessionResumeHelperTests(TestCase):
def test_resume_dispatch_v1(self):
helper1 = SessionResumeHelper1
with mock.patch.object(helper1, 'resume_json'):
data = gzip.compress(
b'{"session":{"desired_job_list":[],"jobs":{},"metadata":'
b'{"app_blob":null,"flags":[],"running_job_name":null,'
b'"title":null},"results":{}},"version":1}')
SessionResumeHelper([], None, None).resume(data)
helper1.resume_json.assert_called_once_with(
{'session': {'jobs': {},
'metadata': {'title': None,
'running_job_name': None,
'app_blob': None,
'flags': []},
'desired_job_list': [],
'results': {}},
'version': 1}, None)
def test_resume_dispatch_v2(self):
helper2 = SessionResumeHelper2
with mock.patch.object(helper2, 'resume_json'):
data = gzip.compress(
b'{"session":{"desired_job_list":[],"jobs":{},"metadata":'
b'{"app_blob":null,"flags":[],"running_job_name":null,'
b'"title":null},"results":{}},"version":2}')
SessionResumeHelper([], None, None).resume(data)
helper2.resume_json.assert_called_once_with(
{'session': {'jobs': {},
'metadata': {'title': None,
'running_job_name': None,
'app_blob': None,
'flags': []},
'desired_job_list': [],
'results': {}},
'version': 2}, None)
def test_resume_dispatch_v3(self):
helper3 = SessionResumeHelper3
with mock.patch.object(helper3, 'resume_json'):
data = gzip.compress(
b'{"session":{"desired_job_list":[],"jobs":{},"metadata":'
b'{"app_blob":null,"app_id":null,"flags":[],'
b'"running_job_name":null,"title":null'
b'},"results":{}},"version":3}')
SessionResumeHelper([], None, None).resume(data)
helper3.resume_json.assert_called_once_with(
{'session': {'jobs': {},
'metadata': {'title': None,
'app_id': None,
'running_job_name': None,
'app_blob': None,
'flags': []},
'desired_job_list': [],
'results': {}},
'version': 3}, None)
def test_resume_dispatch_v4(self):
helper4 = SessionResumeHelper4
with mock.patch.object(helper4, 'resume_json'):
data = gzip.compress(
b'{"session":{"desired_job_list":[],"jobs":{},"metadata":'
b'{"app_blob":null,"app_id":null,"flags":[],'
b'"running_job_name":null,"title":null'
b'},"results":{}},"version":4}')
SessionResumeHelper([], None, None).resume(data)
helper4.resume_json.assert_called_once_with(
{'session': {'jobs': {},
'metadata': {'title': None,
'app_id': None,
'running_job_name': None,
'app_blob': None,
'flags': []},
'desired_job_list': [],
'results': {}},
'version': 4}, None)
def test_resume_dispatch_v5(self):
helper5 = SessionResumeHelper5
with mock.patch.object(helper5, 'resume_json'):
data = gzip.compress(
b'{"session":{"desired_job_list":[],"jobs":{},"metadata":'
b'{"app_blob":null,"app_id":null,"flags":[],'
b'"running_job_name":null,"title":null'
b'},"results":{}},"version":5}')
SessionResumeHelper([], None, None).resume(data)
helper5.resume_json.assert_called_once_with(
{'session': {'jobs': {},
'metadata': {'title': None,
'app_id': None,
'running_job_name': None,
'app_blob': None,
'flags': []},
'desired_job_list': [],
'results': {}},
'version': 5}, None)
def test_resume_dispatch_v6(self):
helper6 = SessionResumeHelper6
with mock.patch.object(helper6, 'resume_json'):
data = gzip.compress(
b'{"session":{"desired_job_list":[],"jobs":{},"metadata":'
b'{"app_blob":null,"app_id":null,"flags":[],'
b'"running_job_name":null,"title":null'
b'},"results":{}},"version":6}')
SessionResumeHelper([], None, None).resume(data)
helper6.resume_json.assert_called_once_with(
{'session': {'jobs': {},
'metadata': {'title': None,
'app_id': None,
'running_job_name': None,
'app_blob': None,
'flags': []},
'desired_job_list': [],
'results': {}},
'version': 6}, None)
def test_resume_dispatch_v7(self):
data = gzip.compress(
b'{"version":7}')
with self.assertRaises(IncompatibleSessionError) as boom:
SessionResumeHelper([], None, None).resume(data)
self.assertEqual(str(boom.exception), "Unsupported version 7")
class SessionPeekHelperTests(TestCase):
def test_peek_dispatch_v1(self):
helper1 = SessionPeekHelper1
with mock.patch.object(helper1, 'peek_json'):
data = gzip.compress(
b'{"session":{"desired_job_list":[],"jobs":{},"metadata":'
b'{"app_blob":null,"flags":[],"running_job_name":null,'
b'"title":null},"results":{}},"version":1}')
SessionPeekHelper().peek(data)
helper1.peek_json.assert_called_once_with(
{'session': {'jobs': {},
'metadata': {'title': None,
'running_job_name': None,
'app_blob': None,
'flags': []},
'desired_job_list': [],
'results': {}},
'version': 1})
def test_peek_dispatch_v2(self):
helper2 = SessionPeekHelper2
with mock.patch.object(helper2, 'peek_json'):
data = gzip.compress(
b'{"session":{"desired_job_list":[],"jobs":{},"metadata":'
b'{"app_blob":null,"flags":[],"running_job_name":null,'
b'"title":null},"results":{}},"version":2}')
SessionPeekHelper().peek(data)
helper2.peek_json.assert_called_once_with(
{'session': {'jobs': {},
'metadata': {'title': None,
'running_job_name': None,
'app_blob': None,
'flags': []},
'desired_job_list': [],
'results': {}},
'version': 2})
def test_peek_dispatch_v3(self):
helper3 = SessionPeekHelper3
with mock.patch.object(helper3, 'peek_json'):
data = gzip.compress(
b'{"session":{"desired_job_list":[],"jobs":{},"metadata":'
b'{"app_blob":null,"flags":[],"running_job_name":null,'
b'"title":null},"results":{}},"version":3}')
SessionPeekHelper().peek(data)
helper3.peek_json.assert_called_once_with(
{'session': {'jobs': {},
'metadata': {'title': None,
'running_job_name': None,
'app_blob': None,
'flags': []},
'desired_job_list': [],
'results': {}},
'version': 3})
def test_peek_dispatch_v4(self):
helper4 = SessionPeekHelper4
with mock.patch.object(helper4, 'peek_json'):
data = gzip.compress(
b'{"session":{"desired_job_list":[],"jobs":{},"metadata":'
b'{"app_blob":null,"flags":[],"running_job_name":null,'
b'"title":null},"results":{}},"version":4}')
SessionPeekHelper().peek(data)
helper4.peek_json.assert_called_once_with(
{'session': {'jobs': {},
'metadata': {'title': None,
'running_job_name': None,
'app_blob': None,
'flags': []},
'desired_job_list': [],
'results': {}},
'version': 4})
def test_peek_dispatch_v5(self):
helper5 = SessionPeekHelper5
with mock.patch.object(helper5, 'peek_json'):
data = gzip.compress(
b'{"session":{"desired_job_list":[],"jobs":{},"metadata":'
b'{"app_blob":null,"flags":[],"running_job_name":null,'
b'"title":null},"results":{}},"version":5}')
SessionPeekHelper().peek(data)
helper5.peek_json.assert_called_once_with(
{'session': {'jobs': {},
'metadata': {'title': None,
'running_job_name': None,
'app_blob': None,
'flags': []},
'desired_job_list': [],
'results': {}},
'version': 5})
def test_peek_dispatch_v6(self):
helper6 = SessionPeekHelper6
with mock.patch.object(helper6, 'peek_json'):
data = gzip.compress(
b'{"session":{"desired_job_list":[],"jobs":{},"metadata":'
b'{"app_blob":null,"flags":[],"running_job_name":null,'
b'"title":null},"results":{}},"version":6}')
SessionPeekHelper().peek(data)
helper6.peek_json.assert_called_once_with(
{'session': {'jobs': {},
'metadata': {'title': None,
'running_job_name': None,
'app_blob': None,
'flags': []},
'desired_job_list': [],
'results': {}},
'version': 6})
class SessionResumeTests(TestCase):
"""
Tests for :class:`~plainbox.impl.session.resume.SessionResumeHelper`
"""
def test_resume_garbage_gzip(self):
"""
verify that CorruptedSessionError raised when we try to decompress
garbage bytes. By "garbage" we mean that it's not a valid
gzip-compressed stream. Internally IOError is raised but we wrap
that for simplicity.
"""
data = b"foo"
with self.assertRaises(CorruptedSessionError) as boom:
SessionResumeHelper([], None, None).resume(data)
self.assertIsInstance(boom.exception.__context__, IOError)
def test_resume_garbage_unicode(self):
"""
verify that CorruptedSessionError is raised when we try to interpret
incorrect bytes as UTF-8. Internally UnicodeDecodeError is raised
but we wrap that for simplicity.
"""
# This is just a sanity check that b"\xff" is not a valid UTF-8 string
with self.assertRaises(UnicodeDecodeError):
b"\xff".decode('UTF-8')
data = gzip.compress(b"\xff")
with self.assertRaises(CorruptedSessionError) as boom:
SessionResumeHelper([], None, None).resume(data)
self.assertIsInstance(boom.exception.__context__, UnicodeDecodeError)
def test_resume_garbage_json(self):
"""
verify that CorruptedSessionError is raised when we try to interpret
malformed JSON text. Internally ValueError is raised but we wrap that
for simplicity.
"""
data = gzip.compress(b"{")
with self.assertRaises(CorruptedSessionError) as boom:
SessionResumeHelper([], None, None).resume(data)
self.assertIsInstance(boom.exception.__context__, ValueError)
class EndToEndTests(TestCaseWithParameters):
parameter_names = ('format',)
parameter_values = (('1',), ('2',), ('3',))
full_repr_1 = {
'version': 1,
'session': {
'jobs': {
'__category__': (
'e2475434e4c0b2c825541430e526fe0565780dfeb67'
'050f3b7f3453aa3cc439b'),
'generator': (
'7015c949ce3ae91f37e10b304212022fdbc4b10acbc'
'cb78ac58ff10ef7a2c8c8'),
'generated': (
'47dd5e318ef99184e4dee8adf818a7f7548978a9470'
'8114c7b3dd2169b9a7a67')
},
'results': {
'__category__': [{
'comments': None,
'execution_duration': None,
'io_log': [
[0.0, 'stdout', 'cGx1Z2luOmxvY2FsCg=='],
[0.1, 'stdout', 'aWQ6Z2VuZXJhdG9yCg=='],
[0.2, 'stdout', 'Y29tbWFuZDpmYWtlCg==']],
'outcome': None,
'return_code': None,
}],
'generator': [{
'comments': None,
'execution_duration': None,
'io_log': [
[0.0, 'stdout', 'aWQ6Z2VuZXJhdGVk'],
[0.1, 'stdout', 'cGx1Z2luOnNoZWxs'],
[0.2, 'stdout', 'Y29tbWFuZDpmYWtl']],
'outcome': None,
'return_code': None,
}],
'generated': [{
'comments': None,
'execution_duration': None,
'io_log': [],
'outcome': None,
'return_code': None,
}]
},
'desired_job_list': ['__category__', 'generator'],
'mandatory_job_list': [],
'metadata': {
'flags': [],
'running_job_name': None,
'title': None
},
}
}
# Copy and patch the v1 representation to get a v2 representation
full_repr_2 = copy.deepcopy(full_repr_1)
full_repr_2['version'] = 2
full_repr_2['session']['metadata']['app_blob'] = None
# Copy and patch the v2 representation to get a v3 representation
full_repr_3 = copy.deepcopy(full_repr_2)
full_repr_3['version'] = 3
full_repr_3['session']['metadata']['app_id'] = None
# Map of representation ids to representations
full_repr = {
'1': full_repr_1,
'2': full_repr_2,
'3': full_repr_3
}
def setUp(self):
# Crete a "__category__" job
self.category_job = JobDefinition({
"plugin": "local",
"id": "__category__"
})
# Create a "generator" job
self.generator_job = JobDefinition({
"plugin": "local",
"id": "generator",
"command": "fake",
})
# Keep a variable for the (future) generated job
self.generated_job = None
# Create a result for the "__category__" job.
# It must define a verbatim copy of the "generator" job
self.category_result = MemoryJobResult({
"io_log": [
(0.0, "stdout", b'plugin:local\n'),
(0.1, "stdout", b'id:generator\n'),
(0.2, "stdout", b'command:fake\n'),
]
})
# Create a result for the "generator" job.
# It will define the "generated" job
self.generator_result = MemoryJobResult({
"io_log": [
(0.0, 'stdout', b'id:generated'),
(0.1, 'stdout', b'plugin:shell'),
(0.2, 'stdout', b'command:fake'),
]
})
self.job_list = [self.category_job, self.generator_job]
self.suspend_data = gzip.compress(
json.dumps(self.full_repr[self.parameters.format]).encode("UTF-8"))
def test_resume_early_callback(self):
"""
verify that early_cb is called with a session object
"""
def early_cb(session):
self.seen_session = session
session = SessionResumeHelper(self.job_list, None, None).resume(
self.suspend_data, early_cb)
self.assertIs(session, self.seen_session)
class SessionStateResumeTests(TestCaseWithParameters):
"""
Tests for :class:`~plainbox.impl.session.resume.SessionResumeHelper1`,
:class:`~plainbox.impl.session.resume.SessionResumeHelper2' and
:class:`~plainbox.impl.session.resume.SessionResumeHelper3' and how they
handle resuming SessionState inside _build_SessionState() method.
"""
parameter_names = ('resume_cls',)
parameter_values = ((SessionResumeHelper1,), (SessionResumeHelper2,),
(SessionResumeHelper3,), (SessionResumeHelper4,),
(SessionResumeHelper5,), (SessionResumeHelper6,))
def setUp(self):
self.session_repr = {}
self.helper = self.parameters.resume_cls([], None, None)
def test_calls_build_SessionState(self):
"""
verify that _build_SessionState() gets called
"""
with mock.patch.object(self.helper, attribute='_build_SessionState'):
self.helper._build_SessionState(self.session_repr)
self.helper._build_SessionState.assert_called_once_with(
self.session_repr)
def test_calls_restore_SessionState_jobs_and_results(self):
"""
verify that _restore_SessionState_jobs_and_results() gets called by
_build_SessionState().
"""
mpo = mock.patch.object
with mpo(self.helper, '_restore_SessionState_jobs_and_results'), \
mpo(self.helper, '_restore_SessionState_metadata'), \
mpo(self.helper, '_restore_SessionState_job_list'), \
mpo(self.helper, '_restore_SessionState_mandatory_job_list'), \
mpo(self.helper, '_restore_SessionState_desired_job_list'):
session = self.helper._build_SessionState(self.session_repr)
self.helper._restore_SessionState_jobs_and_results. \
assert_called_once_with(session, self.session_repr)
def test_calls_restore_SessionState_metadata(self):
"""
verify that _restore_SessionState_metadata() gets called by
_build_SessionState().
"""
mpo = mock.patch.object
with mpo(self.helper, '_restore_SessionState_jobs_and_results'), \
mpo(self.helper, '_restore_SessionState_metadata'), \
mpo(self.helper, '_restore_SessionState_job_list'), \
mpo(self.helper, '_restore_SessionState_mandatory_job_list'), \
mpo(self.helper, '_restore_SessionState_desired_job_list'):
session = self.helper._build_SessionState(self.session_repr)
self.helper._restore_SessionState_metadata. \
assert_called_once_with(session.metadata, self.session_repr)
def test_calls_restore_SessionState_desired_job_list(self):
"""
verify that _restore_SessionState_desired_job_list() gets called by
_build_SessionState().
"""
mpo = mock.patch.object
with mpo(self.helper, '_restore_SessionState_jobs_and_results'), \
mpo(self.helper, '_restore_SessionState_metadata'), \
mpo(self.helper, '_restore_SessionState_job_list'), \
mpo(self.helper, '_restore_SessionState_mandatory_job_list'), \
mpo(self.helper, '_restore_SessionState_desired_job_list'):
session = self.helper._build_SessionState(self.session_repr)
self.helper._restore_SessionState_desired_job_list. \
assert_called_once_with(session, self.session_repr)
def test_calls_restore_SessionState_job_list(self):
"""
verify that _restore_SessionState_job_list() gets called by
_build_SessionState().
"""
mpo = mock.patch.object
with mpo(self.helper, '_restore_SessionState_jobs_and_results'), \
mpo(self.helper, '_restore_SessionState_metadata'), \
mpo(self.helper, '_restore_SessionState_job_list'), \
mpo(self.helper, '_restore_SessionState_mandatory_job_list'), \
mpo(self.helper, '_restore_SessionState_desired_job_list'):
session = self.helper._build_SessionState(self.session_repr)
self.helper._restore_SessionState_job_list.assert_called_once_with(
session, self.session_repr)
class IOLogRecordResumeTests(TestCaseWithParameters):
"""
Tests for :class:`~plainbox.impl.session.resume.SessionResumeHelper1`,
:class:`~plainbox.impl.session.resume.SessionResumeHelper2' and
:class:`~plainbox.impl.session.resume.SessionResumeHelper3' and how they
handle resuming IOLogRecord objects
"""
parameter_names = ('resume_cls',)
parameter_values = ((SessionResumeHelper1,), (SessionResumeHelper2,),
(SessionResumeHelper3,), (SessionResumeHelper4,),
(SessionResumeHelper5,), (SessionResumeHelper6,))
def test_build_IOLogRecord_missing_delay(self):
"""
verify that _build_IOLogRecord() checks for missing ``delay``
"""
with self.assertRaises(CorruptedSessionError):
self.parameters.resume_cls._build_IOLogRecord([])
def test_build_IOLogRecord_bad_type_for_delay(self):
"""
verify that _build_IOLogRecord() checks that ``delay`` is float
"""
with self.assertRaises(CorruptedSessionError):
self.parameters.resume_cls._build_IOLogRecord([0, 'stdout', ''])
def test_build_IOLogRecord_negative_delay(self):
"""
verify that _build_IOLogRecord() checks for negative ``delay``
"""
with self.assertRaises(CorruptedSessionError):
self.parameters.resume_cls._build_IOLogRecord([-1.0, 'stdout', ''])
def test_build_IOLogRecord_missing_stream_name(self):
"""
verify that _build_IOLogRecord() checks for missing ``stream-name``
"""
with self.assertRaises(CorruptedSessionError):
self.parameters.resume_cls._build_IOLogRecord([0.0])
def test_build_IOLogRecord_bad_type_stream_name(self):
"""
verify that _build_IOLogRecord() checks that ``stream-name``
is a string
"""
with self.assertRaises(CorruptedSessionError):
self.parameters.resume_cls._build_IOLogRecord([0.0, 1])
def test_build_IOLogRecord_bad_value_stream_name(self):
"""
verify that _build_IOLogRecord() checks that ``stream-name`` looks sane
"""
with self.assertRaises(CorruptedSessionError):
self.parameters.resume_cls._build_IOLogRecord([0.0, "foo", ""])
def test_build_IOLogRecord_missing_data(self):
"""
verify that _build_IOLogRecord() checks for missing ``data``
"""
with self.assertRaises(CorruptedSessionError):
self.parameters.resume_cls._build_IOLogRecord([0.0, 'stdout'])
def test_build_IOLogRecord_non_ascii_data(self):
"""
verify that _build_IOLogRecord() checks that ``data`` is ASCII
"""
with self.assertRaises(CorruptedSessionError) as boom:
self.parameters.resume_cls._build_IOLogRecord(
[0.0, 'stdout', '\uFFFD'])
self.assertIsInstance(boom.exception.__context__, UnicodeEncodeError)
def test_build_IOLogRecord_non_base64_ascii_data(self):
"""
verify that _build_IOLogRecord() checks that ``data`` is valid base64
"""
with self.assertRaises(CorruptedSessionError) as boom:
self.parameters.resume_cls._build_IOLogRecord(
[0.0, 'stdout', '==broken'])
# base64.standard_b64decode() raises binascii.Error
self.assertIsInstance(boom.exception.__context__, binascii.Error)
def test_build_IOLogRecord_values(self):
"""
verify that _build_IOLogRecord() returns a proper IOLogRecord object
with all the values in order
"""
record = self.parameters.resume_cls._build_IOLogRecord(
[1.5, 'stderr', 'dGhpcyB3b3Jrcw=='])
self.assertAlmostEqual(record.delay, 1.5)
self.assertEqual(record.stream_name, 'stderr')
self.assertEqual(record.data, b"this works")
class JobResultResumeMixIn:
"""
Mix-in class the defines most of the common tests for both
MemoryJobResult and DiskJobResult.
Sub-classes should define ``good_repr`` at class level
"""
good_repr = None
def test_build_JobResult_checks_for_missing_outcome(self):
"""
verify that _build_JobResult() checks if ``outcome`` is present
"""
with self.assertRaises(CorruptedSessionError) as boom:
obj_repr = copy.copy(self.good_repr)
del obj_repr['outcome']
self.parameters.resume_cls._build_JobResult(obj_repr, 0, None)
self.assertEqual(
str(boom.exception), "Missing value for key 'outcome'")
def test_build_JobResult_checks_type_of_outcome(self):
"""
verify that _build_JobResult() checks if ``outcome`` is a string
"""
with self.assertRaises(CorruptedSessionError) as boom:
obj_repr = copy.copy(self.good_repr)
obj_repr['outcome'] = 42
self.parameters.resume_cls._build_JobResult(obj_repr, 0, None)
self.assertEqual(
str(boom.exception),
"Value of key 'outcome' is of incorrect type int")
def test_build_JobResult_checks_value_of_outcome(self):
"""
verify that _build_JobResult() checks if the value of ``outcome`` is
in the set of known-good values.
"""
with self.assertRaises(CorruptedSessionError) as boom:
obj_repr = copy.copy(self.good_repr)
obj_repr['outcome'] = 'maybe'
self.parameters.resume_cls._build_JobResult(obj_repr, 0, None)
self.assertEqual(
str(boom.exception), (
"Value for key 'outcome' not in allowed set ['crash', 'fail',"
" None, 'not-implemented', 'not-supported', 'pass', 'skip', "
"'undecided']"))
def test_build_JobResult_allows_none_outcome(self):
"""
verify that _build_JobResult() allows for the value of ``outcome`` to
be None
"""
obj_repr = copy.copy(self.good_repr)
obj_repr['outcome'] = None
obj = self.parameters.resume_cls._build_JobResult(obj_repr, 0, None)
self.assertEqual(obj.outcome, None)
def test_build_JobResult_restores_outcome(self):
"""
verify that _build_JobResult() restores the value of ``outcome``
"""
obj_repr = copy.copy(self.good_repr)
obj_repr['outcome'] = 'fail'
obj = self.parameters.resume_cls._build_JobResult(obj_repr, 0, None)
self.assertEqual(obj.outcome, 'fail')
def test_build_JobResult_checks_for_missing_comments(self):
"""
verify that _build_JobResult() checks if ``comments`` is present
"""
with self.assertRaises(CorruptedSessionError) as boom:
obj_repr = copy.copy(self.good_repr)
del obj_repr['comments']
self.parameters.resume_cls._build_JobResult(obj_repr, 0, None)
self.assertEqual(
str(boom.exception), "Missing value for key 'comments'")
def test_build_JobResult_checks_type_of_comments(self):
"""
verify that _build_JobResult() checks if ``comments`` is a string
"""
with self.assertRaises(CorruptedSessionError) as boom:
obj_repr = copy.copy(self.good_repr)
obj_repr['comments'] = False
self.parameters.resume_cls._build_JobResult(obj_repr, 0, None)
self.assertEqual(
str(boom.exception),
"Value of key 'comments' is of incorrect type bool")
def test_build_JobResult_allows_for_none_comments(self):
"""
verify that _build_JobResult() allows for the value of ``comments``
to be None
"""
obj_repr = copy.copy(self.good_repr)
obj_repr['comments'] = None
obj = self.parameters.resume_cls._build_JobResult(obj_repr, 0, None)
self.assertEqual(obj.comments, None)
def test_build_JobResult_restores_comments(self):
"""
verify that _build_JobResult() restores the value of ``comments``
"""
obj_repr = copy.copy(self.good_repr)
obj_repr['comments'] = 'this is a comment'
obj = self.parameters.resume_cls._build_JobResult(obj_repr, 0, None)
self.assertEqual(obj.comments, 'this is a comment')
def test_build_JobResult_checks_for_missing_return_code(self):
"""
verify that _build_JobResult() checks if ``return_code`` is present
"""
with self.assertRaises(CorruptedSessionError) as boom:
obj_repr = copy.copy(self.good_repr)
del obj_repr['return_code']
self.parameters.resume_cls._build_JobResult(obj_repr, 0, None)
self.assertEqual(
str(boom.exception), "Missing value for key 'return_code'")
def test_build_JobResult_checks_type_of_return_code(self):
"""
verify that _build_JobResult() checks if ``return_code`` is an integer
"""
with self.assertRaises(CorruptedSessionError) as boom:
obj_repr = copy.copy(self.good_repr)
obj_repr['return_code'] = "text"
self.parameters.resume_cls._build_JobResult(obj_repr, 0, None)
self.assertEqual(
str(boom.exception),
"Value of key 'return_code' is of incorrect type str")
def test_build_JobResult_allows_for_none_return_code(self):
"""
verify that _build_JobResult() allows for the value of ``return_code``
to be None
"""
obj_repr = copy.copy(self.good_repr)
obj_repr['return_code'] = None
obj = self.parameters.resume_cls._build_JobResult(obj_repr, 0, None)
self.assertEqual(obj.return_code, None)
def test_build_JobResult_restores_return_code(self):
"""
verify that _build_JobResult() restores the value of ``return_code``
"""
obj_repr = copy.copy(self.good_repr)
obj_repr['return_code'] = 42
obj = self.parameters.resume_cls._build_JobResult(obj_repr, 0, None)
self.assertEqual(obj.return_code, 42)
def test_build_JobResult_checks_for_missing_execution_duration(self):
"""
verify that _build_JobResult() checks if ``execution_duration``
is present
"""
with self.assertRaises(CorruptedSessionError) as boom:
obj_repr = copy.copy(self.good_repr)
del obj_repr['execution_duration']
self.parameters.resume_cls._build_JobResult(obj_repr, 0, None)
self.assertEqual(
str(boom.exception), "Missing value for key 'execution_duration'")
def test_build_JobResult_checks_type_of_execution_duration(self):
"""
verify that _build_JobResult() checks if ``execution_duration``
is a float
"""
with self.assertRaises(CorruptedSessionError) as boom:
obj_repr = copy.copy(self.good_repr)
obj_repr['execution_duration'] = "text"
self.parameters.resume_cls._build_JobResult(obj_repr, 0, None)
self.assertEqual(
str(boom.exception),
"Value of key 'execution_duration' is of incorrect type str")
def test_build_JobResult_allows_for_none_execution_duration(self):
"""
verify that _build_JobResult() allows for the value of
``execution_duration`` to be None
"""
obj_repr = copy.copy(self.good_repr)
obj_repr['execution_duration'] = None
obj = self.parameters.resume_cls._build_JobResult(obj_repr, 0, None)
self.assertEqual(obj.execution_duration, None)
def test_build_JobResult_restores_execution_duration(self):
"""
verify that _build_JobResult() restores the value of
``execution_duration``
"""
obj_repr = copy.copy(self.good_repr)
obj_repr['execution_duration'] = 5.1
obj = self.parameters.resume_cls._build_JobResult(obj_repr, 0, None)
self.assertAlmostEqual(obj.execution_duration, 5.1)
class MemoryJobResultResumeTests(JobResultResumeMixIn, TestCaseWithParameters):
"""
Tests for :class:`~plainbox.impl.session.resume.SessionResumeHelper1`,
:class:`~plainbox.impl.session.resume.SessionResumeHelper2' and
:class:`~plainbox.impl.session.resume.SessionResumeHelper3' and how they
handle recreating MemoryJobResult form their representations
"""
parameter_names = ('resume_cls',)
parameter_values = ((SessionResumeHelper1,), (SessionResumeHelper2,),
(SessionResumeHelper3,), (SessionResumeHelper4,),
(SessionResumeHelper5,), (SessionResumeHelper6,))
good_repr = {
'outcome': "pass",
'comments': None,
'return_code': None,
'execution_duration': None,
'io_log': []
}
def test_build_JobResult_restores_MemoryJobResult_representations(self):
obj = self.parameters.resume_cls._build_JobResult(
self.good_repr, 0, None)
self.assertIsInstance(obj, MemoryJobResult)
def test_build_JobResult_checks_for_missing_io_log(self):
"""
verify that _build_JobResult() checks if ``io_log`` is present
"""
with self.assertRaises(CorruptedSessionError) as boom:
obj_repr = copy.copy(self.good_repr)
del obj_repr['io_log']
self.parameters.resume_cls._build_JobResult(obj_repr, 0, None)
self.assertEqual(
str(boom.exception), "Missing value for key 'io_log'")
def test_build_JobResult_checks_type_of_io_log(self):
"""
verify that _build_JobResult() checks if ``io_log``
is a list
"""
with self.assertRaises(CorruptedSessionError) as boom:
obj_repr = copy.copy(self.good_repr)
obj_repr['io_log'] = "text"
self.parameters.resume_cls._build_JobResult(obj_repr, 0, None)
self.assertEqual(
str(boom.exception),
"Value of key 'io_log' is of incorrect type str")
def test_build_JobResult_checks_for_none_io_log(self):
"""
verify that _build_JobResult() checks if the value of
``io_log`` is not None
"""
with self.assertRaises(CorruptedSessionError) as boom:
obj_repr = copy.copy(self.good_repr)
obj_repr['io_log'] = None
self.parameters.resume_cls._build_JobResult(obj_repr, 0, None)
self.assertEqual(
str(boom.exception),
"Value of key 'io_log' cannot be None")
def test_build_JobResult_restores_io_log(self):
"""
verify that _build_JobResult() checks if ``io_log``
is restored for MemoryJobResult representations
"""
obj_repr = copy.copy(self.good_repr)
obj_repr['io_log'] = [[0.0, 'stdout', '']]
obj = self.parameters.resume_cls._build_JobResult(obj_repr, 0, None)
# NOTE: MemoryJobResult.io_log is a property that converts
# whatever was stored to IOLogRecord and returns a _tuple_
# so the original list is not visible
self.assertEqual(obj.io_log, tuple([
IOLogRecord(0.0, 'stdout', b'')
]))
class DiskJobResultResumeTestsCommon(JobResultResumeMixIn,
TestCaseWithParameters):
""" Tests for common behavior of DiskJobResult resume for all formats. """
parameter_names = ('resume_cls',)
parameter_values = ((SessionResumeHelper1,), (SessionResumeHelper2,),
(SessionResumeHelper3,), (SessionResumeHelper4,),
(SessionResumeHelper5,), (SessionResumeHelper6,))
good_repr = {
'outcome': "pass",
'comments': None,
'return_code': None,
'execution_duration': None,
# NOTE: path is absolute (realistic data required by most of tests)
'io_log_filename': "/file.txt"
}
def test_build_JobResult_restores_DiskJobResult_representations(self):
obj = self.parameters.resume_cls._build_JobResult(
self.good_repr, 0, None)
self.assertIsInstance(obj, DiskJobResult)
def test_build_JobResult_does_not_check_for_missing_io_log_filename(self):
"""
verify that _build_JobResult() does not check if
``io_log_filename`` is present as that signifies that MemoryJobResult
should be recreated instead
"""
with self.assertRaises(CorruptedSessionError) as boom:
obj_repr = copy.copy(self.good_repr)
del obj_repr['io_log_filename']
self.parameters.resume_cls._build_JobResult(obj_repr, 0, None)
# NOTE: the error message explicitly talks about 'io_log', not
# about 'io_log_filename' because we're hitting the other path
# of the restore function
self.assertEqual(
str(boom.exception), "Missing value for key 'io_log'")
def test_build_JobResult_checks_type_of_io_log_filename(self):
"""
verify that _build_JobResult() checks if ``io_log_filename``
is a string
"""
with self.assertRaises(CorruptedSessionError) as boom:
obj_repr = copy.copy(self.good_repr)
obj_repr['io_log_filename'] = False
self.parameters.resume_cls._build_JobResult(obj_repr, 0, None)
self.assertEqual(
str(boom.exception),
"Value of key 'io_log_filename' is of incorrect type bool")
def test_build_JobResult_checks_for_none_io_log_filename(self):
"""
verify that _build_JobResult() checks if the value of
``io_log_filename`` is not None
"""
with self.assertRaises(CorruptedSessionError) as boom:
obj_repr = copy.copy(self.good_repr)
obj_repr['io_log_filename'] = None
self.parameters.resume_cls._build_JobResult(obj_repr, 0, None)
self.assertEqual(
str(boom.exception),
"Value of key 'io_log_filename' cannot be None")
class DiskJobResultResumeTests1to4(TestCaseWithParameters):
""" Tests for behavior of DiskJobResult resume for formats 1 to 4. """
parameter_names = ('resume_cls',)
parameter_values = ((SessionResumeHelper1,), (SessionResumeHelper2,),
(SessionResumeHelper3,), (SessionResumeHelper4,))
good_repr = {
'outcome': "pass",
'comments': None,
'return_code': None,
'execution_duration': None,
'io_log_filename': "/file.txt"
}
def test_build_JobResult_restores_io_log_filename(self):
""" _build_JobResult() accepts relative paths without location. """
obj_repr = copy.copy(self.good_repr)
obj_repr['io_log_filename'] = "some-file.txt"
obj = self.parameters.resume_cls._build_JobResult(obj_repr, 0, None)
self.assertEqual(obj.io_log_filename, "some-file.txt")
def test_build_JobResult_restores_relative_io_log_filename(self):
""" _build_JobResult() ignores location for relative paths. """
obj_repr = copy.copy(self.good_repr)
obj_repr['io_log_filename'] = "some-file.txt"
obj = self.parameters.resume_cls._build_JobResult(
obj_repr, 0, '/path/to')
self.assertEqual(obj.io_log_filename, "some-file.txt")
def test_build_JobResult_restores_absolute_io_log_filename(self):
""" _build_JobResult() preserves absolute paths. """
obj_repr = copy.copy(self.good_repr)
obj_repr['io_log_filename'] = "/some-file.txt"
obj = self.parameters.resume_cls._build_JobResult(
obj_repr, 0, '/path/to')
self.assertEqual(obj.io_log_filename, "/some-file.txt")
class DiskJobResultResumeTests5(TestCaseWithParameters):
""" Tests for behavior of DiskJobResult resume for format 5. """
parameter_names = ('resume_cls',)
parameter_values = ((SessionResumeHelper6,),)
good_repr = {
'outcome': "pass",
'comments': None,
'return_code': None,
'execution_duration': None,
'io_log_filename': "/file.txt"
}
def test_build_JobResult_restores_io_log_filename(self):
""" _build_JobResult() rejects relative paths without location. """
obj_repr = copy.copy(self.good_repr)
obj_repr['io_log_filename'] = "some-file.txt"
with self.assertRaisesRegex(ValueError, "Location "):
self.parameters.resume_cls._build_JobResult(obj_repr, 0, None)
def test_build_JobResult_restores_relative_io_log_filename(self):
""" _build_JobResult() uses location for relative paths. """
obj_repr = copy.copy(self.good_repr)
obj_repr['io_log_filename'] = "some-file.txt"
obj = self.parameters.resume_cls._build_JobResult(
obj_repr, 0, '/path/to')
self.assertEqual(obj.io_log_filename, "/path/to/some-file.txt")
def test_build_JobResult_restores_absolute_io_log_filename(self):
""" _build_JobResult() preserves absolute paths. """
obj_repr = copy.copy(self.good_repr)
obj_repr['io_log_filename'] = "/some-file.txt"
obj = self.parameters.resume_cls._build_JobResult(
obj_repr, 0, '/path/to')
self.assertEqual(obj.io_log_filename, "/some-file.txt")
class DesiredJobListResumeTests(TestCaseWithParameters):
"""
Tests for :class:`~plainbox.impl.session.resume.SessionResumeHelper1`,
:class:`~plainbox.impl.session.resume.SessionResumeHelper2' and
:class:`~plainbox.impl.session.resume.SessionResumeHelper3' and how they
handle recreating SessionState.desired_job_list form its representation
"""
parameter_names = ('resume_cls',)
parameter_values = ((SessionResumeHelper1,), (SessionResumeHelper2,),
(SessionResumeHelper3,), (SessionResumeHelper4,),
(SessionResumeHelper5,), (SessionResumeHelper6,))
def setUp(self):
# All of the tests need a SessionState object and some jobs to work
# with. Actual values don't matter much.
self.job_a = make_job(id='a')
self.job_b = make_job(id='b')
self.session = SessionState([self.job_a, self.job_b])
self.good_repr = {
"desired_job_list": ['a', 'b']
}
self.resume_fn = (
self.parameters.resume_cls._restore_SessionState_desired_job_list)
def test_restore_SessionState_desired_job_list_checks_for_repr_type(self):
"""
verify that _restore_SessionState_desired_job_list() checks the
type of the representation of ``desired_job_list``.
"""
with self.assertRaises(CorruptedSessionError) as boom:
obj_repr = copy.copy(self.good_repr)
obj_repr['desired_job_list'] = 1
self.resume_fn(self.session, obj_repr)
self.assertEqual(
str(boom.exception),
"Value of key 'desired_job_list' is of incorrect type int")
def test_restore_SessionState_desired_job_list_checks_job_id_type(self):
"""
verify that _restore_SessionState_desired_job_list() checks the
type of each job id listed in ``desired_job_list``.
"""
with self.assertRaises(CorruptedSessionError) as boom:
obj_repr = copy.copy(self.good_repr)
obj_repr['desired_job_list'] = [1]
self.resume_fn(self.session, obj_repr)
self.assertEqual(str(boom.exception), "Each job id must be a string")
def test_restore_SessionState_desired_job_list_checks_for_bogus_jobs(self):
"""
verify that _restore_SessionState_desired_job_list() checks if
each of the mentioned jobs are known and defined in the session
"""
with self.assertRaises(CorruptedSessionError) as boom:
obj_repr = copy.copy(self.good_repr)
obj_repr['desired_job_list'] = ['bogus']
self.resume_fn(self.session, obj_repr)
self.assertEqual(
str(boom.exception),
"'desired_job_list' refers to unknown job 'bogus'")
def test_restore_SessionState_desired_job_list_works(self):
"""
verify that _restore_SessionState_desired_job_list() actually
restores desired_job_list on the session
"""
self.assertEqual(
self.session.desired_job_list, [])
self.resume_fn(self.session, self.good_repr)
# Good representation has two jobs, 'a' and 'b', in that order
self.assertEqual(
self.session.desired_job_list,
[self.job_a, self.job_b])
class SessionMetaDataResumeTests(TestCaseWithParameters):
"""
Tests for :class:`~plainbox.impl.session.resume.SessionResumeHelper1`,
:class:`~plainbox.impl.session.resume.SessionResumeHelper2' and
:class:`~plainbox.impl.session.resume.SessionResumeHelper3' and how they
handle recreating SessionMetaData form its representation
"""
parameter_names = ('format',)
parameter_values = ((1,), (2,), (3,))
good_repr_v1 = {
"metadata": {
"title": "some title",
"flags": ["flag1", "flag2"],
"running_job_name": "job1"
}
}
good_repr_v2 = {
"metadata": {
"title": "some title",
"flags": ["flag1", "flag2"],
"running_job_name": "job1",
"app_blob": None,
}
}
good_repr_v3 = {
"metadata": {
"title": "some title",
"flags": ["flag1", "flag2"],
"running_job_name": "job1",
"app_blob": None,
"app_id": None,
}
}
good_repr_map = {
1: good_repr_v1,
2: good_repr_v2,
3: good_repr_v3
}
resume_cls_map = {
1: SessionResumeHelper1,
2: SessionResumeHelper2,
3: SessionResumeHelper3,
}
def setUp(self):
# All of the tests need a SessionState object
self.session = SessionState([])
self.good_repr = copy.deepcopy(
self.good_repr_map[self.parameters.format])
self.resume_fn = (
self.resume_cls_map[
self.parameters.format
]._restore_SessionState_metadata)
def test_restore_SessionState_metadata_cheks_for_representation_type(self):
"""
verify that _restore_SessionState_metadata() checks the type of
the representation object
"""
with self.assertRaises(CorruptedSessionError) as boom:
self.good_repr['metadata'] = 1
self.resume_fn(self.session.metadata, self.good_repr)
self.assertEqual(
str(boom.exception),
"Value of key 'metadata' is of incorrect type int")
def test_restore_SessionState_metadata_checks_title_type(self):
"""
verify that _restore_SessionState_metadata() checks the type of
the ``title`` field.
"""
with self.assertRaises(CorruptedSessionError) as boom:
self.good_repr['metadata']['title'] = 1
self.resume_fn(self.session.metadata, self.good_repr)
self.assertEqual(
str(boom.exception),
"Value of key 'title' is of incorrect type int")
def test_restore_SessionState_metadata_allows_for_none_title(self):
"""
verify that _restore_SessionState_metadata() allows for
``title`` to be None
"""
self.good_repr['metadata']['title'] = None
self.resume_fn(self.session.metadata, self.good_repr)
self.assertEqual(self.session.metadata.title, None)
def test_restore_SessionState_metadata_restores_title(self):
"""
verify that _restore_SessionState_metadata() restores ``title``
"""
self.good_repr['metadata']['title'] = "a title"
self.resume_fn(self.session.metadata, self.good_repr)
self.assertEqual(self.session.metadata.title, "a title")
def test_restore_SessionState_metadata_checks_flags_type(self):
"""
verify that _restore_SessionState_metadata() checks the type of
the ``flags`` field.
"""
with self.assertRaises(CorruptedSessionError) as boom:
self.good_repr['metadata']['flags'] = 1
self.resume_fn(self.session.metadata, self.good_repr)
self.assertEqual(
str(boom.exception),
"Value of key 'flags' is of incorrect type int")
def test_restore_SessionState_metadata_cheks_if_flags_are_none(self):
"""
verify that _restore_SessionState_metadata() checks if
``flags`` are None
"""
with self.assertRaises(CorruptedSessionError) as boom:
self.good_repr['metadata']['flags'] = None
self.resume_fn(self.session.metadata, self.good_repr)
self.assertEqual(
str(boom.exception),
"Value of key 'flags' cannot be None")
def test_restore_SessionState_metadata_checks_type_of_each_flag(self):
"""
verify that _restore_SessionState_metadata() checks the type of each
value of ``flags``
"""
with self.assertRaises(CorruptedSessionError) as boom:
self.good_repr['metadata']['flags'] = [1]
self.resume_fn(self.session.metadata, self.good_repr)
self.assertEqual(
str(boom.exception),
"Each flag must be a string")
def test_restore_SessionState_metadata_restores_flags(self):
"""
verify that _restore_SessionState_metadata() restores ``flags``
"""
self.good_repr['metadata']['flags'] = ["flag1", "flag2"]
self.resume_fn(self.session.metadata, self.good_repr)
self.assertEqual(self.session.metadata.flags, set(['flag1', 'flag2']))
def test_restore_SessionState_metadata_checks_running_job_name_type(self):
"""
verify that _restore_SessionState_metadata() checks the type of
``running_job_name``.
"""
with self.assertRaises(CorruptedSessionError) as boom:
self.good_repr['metadata']['running_job_name'] = 1
self.resume_fn(self.session.metadata, self.good_repr)
self.assertEqual(
str(boom.exception),
"Value of key 'running_job_name' is of incorrect type int")
def test_restore_SessionState_metadata_allows__none_running_job_name(self):
"""
verify that _restore_SessionState_metadata() allows for
``running_job_name`` to be None
"""
self.good_repr['metadata']['running_job_name'] = None
self.resume_fn(self.session.metadata, self.good_repr)
self.assertEqual(self.session.metadata.running_job_name, None)
def test_restore_SessionState_metadata_restores_running_job_name(self):
"""
verify that _restore_SessionState_metadata() restores
the value of ``running_job_name``
"""
self.good_repr['metadata']['running_job_name'] = "a job"
self.resume_fn(self.session.metadata, self.good_repr)
self.assertEqual(self.session.metadata.running_job_name, "a job")
class SessionMetaDataResumeTests2(TestCase):
"""
Tests for :class:`~plainbox.impl.session.resume.SessionResumeHelper2`
and how it handles recreating SessionMetaData form its representation
"""
def setUp(self):
# All of the tests need a SessionState object
self.session = SessionState([])
self.good_repr = {
"metadata": {
"title": "some title",
"flags": ["flag1", "flag2"],
"running_job_name": "job1",
"app_blob": "YmxvYg==" # this is b'blob', encoded
}
}
self.resume_fn = SessionResumeHelper2._restore_SessionState_metadata
def test_restore_SessionState_metadata_checks_app_blob_type(self):
"""
verify that _restore_SessionState_metadata() checks the type of
the ``app_blob`` field.
"""
with self.assertRaises(CorruptedSessionError) as boom:
obj_repr = copy.copy(self.good_repr)
obj_repr['metadata']['app_blob'] = 1
self.resume_fn(self.session.metadata, obj_repr)
self.assertEqual(
str(boom.exception),
"Value of key 'app_blob' is of incorrect type int")
def test_restore_SessionState_metadata_allows_for_none_app_blob(self):
"""
verify that _restore_SessionState_metadata() allows for
``app_blob`` to be None
"""
obj_repr = copy.copy(self.good_repr)
obj_repr['metadata']['app_blob'] = None
self.resume_fn(self.session.metadata, obj_repr)
self.assertEqual(self.session.metadata.app_blob, None)
def test_restore_SessionState_metadata_restores_app_blob(self):
"""
verify that _restore_SessionState_metadata() restores ``app_blob``
"""
obj_repr = copy.copy(self.good_repr)
obj_repr['metadata']['app_blob'] = "YmxvYg=="
self.resume_fn(self.session.metadata, obj_repr)
self.assertEqual(self.session.metadata.app_blob, b"blob")
def test_restore_SessionState_metadata_non_ascii_app_blob(self):
"""
verify that _restore_SessionState_metadata() checks that ``app_blob``
is ASCII
"""
with self.assertRaises(CorruptedSessionError) as boom:
obj_repr = copy.copy(self.good_repr)
obj_repr['metadata']['app_blob'] = '\uFFFD'
self.resume_fn(self.session.metadata, obj_repr)
self.assertEqual(str(boom.exception), "app_blob is not ASCII")
self.assertIsInstance(boom.exception.__context__, UnicodeEncodeError)
def test_restore_SessionState_metadata_non_base64_app_blob(self):
"""
verify that _restore_SessionState_metadata() checks that ``app_blob``
is valid base64
"""
with self.assertRaises(CorruptedSessionError) as boom:
obj_repr = copy.copy(self.good_repr)
obj_repr['metadata']['app_blob'] = '==broken'
self.resume_fn(self.session.metadata, obj_repr)
self.assertEqual(str(boom.exception), "Cannot base64 decode app_blob")
# base64.standard_b64decode() raises binascii.Error
self.assertIsInstance(boom.exception.__context__, binascii.Error)
class SessionMetaDataResumeTest3(SessionMetaDataResumeTests2):
"""
Tests for :class:`~plainbox.impl.session.resume.SessionResumeHelper3`
and how it handles recreating SessionMetaData form its representation
"""
def setUp(self):
# All of the tests need a SessionState object
self.session = SessionState([])
self.good_repr = {
"metadata": {
"title": "some title",
"flags": ["flag1", "flag2"],
"running_job_name": "job1",
"app_blob": "YmxvYg==", # this is b'blob', encoded
"app_id": "id"
}
}
self.resume_fn = SessionResumeHelper3._restore_SessionState_metadata
def test_restore_SessionState_metadata_checks_app_id_type(self):
"""
verify that _restore_SessionState_metadata() checks the type of
the ``app_id`` field.
"""
with self.assertRaises(CorruptedSessionError) as boom:
obj_repr = copy.copy(self.good_repr)
obj_repr['metadata']['app_id'] = 1
self.resume_fn(self.session.metadata, obj_repr)
self.assertEqual(
str(boom.exception),
"Value of key 'app_id' is of incorrect type int")
def test_restore_SessionState_metadata_allows_for_none_app_id(self):
"""
verify that _restore_SessionState_metadata() allows for
``app_id`` to be None
"""
obj_repr = copy.copy(self.good_repr)
obj_repr['metadata']['app_id'] = None
self.resume_fn(self.session.metadata, obj_repr)
self.assertEqual(self.session.metadata.app_id, None)
def test_restore_SessionState_metadata_restores_app_id(self):
"""
verify that _restore_SessionState_metadata() restores ``app_id``
"""
obj_repr = copy.copy(self.good_repr)
obj_repr['metadata']['app_id'] = "id"
self.resume_fn(self.session.metadata, obj_repr)
self.assertEqual(self.session.metadata.app_id, "id")
class ProcessJobTests(TestCaseWithParameters):
"""
Tests for :class:`~plainbox.impl.session.resume.SessionResumeHelper1`,
:class:`~plainbox.impl.session.resume.SessionResumeHelper2` and
:class:`~plainbox.impl.session.resume.SessionResumeHelper3` and how they
handle processing jobs using _process_job() method
"""
parameter_names = ('resume_cls',)
parameter_values = ((SessionResumeHelper1,), (SessionResumeHelper2,),
(SessionResumeHelper3,), (SessionResumeHelper4,),
(SessionResumeHelper5,), (SessionResumeHelper6,))
def setUp(self):
self.job_id = 'job'
self.job = make_job(id=self.job_id)
self.jobs_repr = {
self.job_id: self.job.checksum
}
self.results_repr = {
self.job_id: [{
'outcome': 'fail',
'comments': None,
'execution_duration': None,
'return_code': None,
'io_log': [],
}]
}
self.helper = self.parameters.resume_cls([self.job], None, None)
# This object is artificial and would be constructed internally
# by the helper but having it here makes testing easier as we
# can reliably test a single method in isolation.
self.session = SessionState([self.job])
def test_process_job_checks_type_of_job_id(self):
"""
verify that _process_job() checks the type of ``job_id``
"""
with self.assertRaises(CorruptedSessionError) as boom:
# Pass a job id of the wrong type
job_id = 1
self.helper._process_job(
self.session, self.jobs_repr, self.results_repr, job_id)
self.assertEqual(
str(boom.exception), "Value of object is of incorrect type int")
def test_process_job_checks_for_missing_checksum(self):
"""
verify that _process_job() checks if ``checksum`` is missing
"""
with self.assertRaises(CorruptedSessionError) as boom:
# Pass a jobs_repr that has no checksums (for any job)
jobs_repr = {}
self.helper._process_job(
self.session, jobs_repr, self.results_repr, self.job_id)
self.assertEqual(str(boom.exception), "Missing value for key 'job'")
def test_process_job_checks_if_job_is_known(self):
"""
verify that _process_job() checks if job is known or raises KeyError
"""
with self.assertRaises(KeyError) as boom:
# Pass a session that does not know about any jobs
session = SessionState([])
self.helper._process_job(
session, self.jobs_repr, self.results_repr, self.job_id)
self.assertEqual(boom.exception.args[0], 'job')
def test_process_job_checks_if_job_checksum_matches(self):
"""
verify that _process_job() checks if job checksum matches the
checksum of a job with the same id that was passed to the helper.
"""
with self.assertRaises(IncompatibleJobError) as boom:
# Pass a jobs_repr with a bad checksum
jobs_repr = {self.job_id: 'bad-checksum'}
self.helper._process_job(
self.session, jobs_repr, self.results_repr, self.job_id)
self.assertEqual(
str(boom.exception), "Definition of job 'job' has changed")
def test_process_job_handles_ignores_empty_results(self):
"""
verify that _process_job() does not crash if we have no results
for a particular job
"""
self.assertEqual(
self.session.job_state_map[self.job_id].result.outcome, None)
results_repr = {
self.job_id: []
}
self.helper._process_job(
self.session, self.jobs_repr, results_repr, self.job_id)
self.assertEqual(
self.session.job_state_map[self.job_id].result.outcome, None)
def test_process_job_handles_only_result_back_to_the_session(self):
"""
verify that _process_job() passes the only result to the session
"""
self.assertEqual(
self.session.job_state_map[self.job_id].result.outcome, None)
self.helper._process_job(
self.session, self.jobs_repr, self.results_repr, self.job_id)
# The result in self.results_repr is a failure so we should see it here
self.assertEqual(
self.session.job_state_map[self.job_id].result.outcome, "fail")
def test_process_job_handles_last_result_back_to_the_session(self):
"""
verify that _process_job() passes last of the results to the session
"""
self.assertEqual(
self.session.job_state_map[self.job_id].result.outcome, None)
results_repr = {
self.job_id: [{
'outcome': 'fail',
'comments': None,
'execution_duration': None,
'return_code': None,
'io_log': [],
}, {
'outcome': 'pass',
'comments': None,
'execution_duration': None,
'return_code': None,
'io_log': [],
}]
}
self.helper._process_job(
self.session, self.jobs_repr, results_repr, self.job_id)
# results_repr has two entries: [fail, pass] so we should see
# the passing entry only
self.assertEqual(
self.session.job_state_map[self.job_id].result.outcome, "pass")
def test_process_job_checks_results_repr_is_a_list(self):
"""
verify that _process_job() checks if results_repr is a dictionary
of lists.
"""
with self.assertRaises(CorruptedSessionError) as boom:
results_repr = {self.job_id: 1}
self.helper._process_job(
self.session, self.jobs_repr, results_repr, self.job_id)
self.assertEqual(
str(boom.exception),
"Value of key 'job' is of incorrect type int")
def test_process_job_checks_results_repr_values_are_dicts(self):
"""
verify that _process_job() checks if results_repr is a dictionary
of lists, each of which holds a dictionary.
"""
with self.assertRaises(CorruptedSessionError) as boom:
results_repr = {self.job_id: [1]}
self.helper._process_job(
self.session, self.jobs_repr, results_repr, self.job_id)
self.assertEqual(
str(boom.exception),
"Value of object is of incorrect type int")
class JobPluginSpecificTests(TestCaseWithParameters):
"""
Tests for :class:`~plainbox.impl.session.resume.SessionResumeHelper1`,
:class:`~plainbox.impl.session.resume.SessionResumeHelper2' and
:class:`~plainbox.impl.session.resume.SessionResumeHelper3' and how they
handle processing jobs using _process_job() method. This class focuses on
plugin-specific test such as for local and resource jobs
"""
parameter_names = ('resume_cls',)
parameter_values = ((SessionResumeHelper1,), (SessionResumeHelper2,),
(SessionResumeHelper3,), (SessionResumeHelper4,),
(SessionResumeHelper5,), (SessionResumeHelper6,))
def test_process_job_restores_resources(self):
"""
verify that _process_job() recreates resources
"""
# Set the stage for testing. Setup a session with a known
# resource job, representation of the job (checksum)
# and representation of a single result, which has a single line
# that defines a 'key': 'value' resource record.
job_id = 'resource'
job = make_job(id=job_id, plugin='resource')
jobs_repr = {
job_id: job.checksum
}
results_repr = {
job_id: [{
'outcome': IJobResult.OUTCOME_PASS,
'comments': None,
'execution_duration': None,
'return_code': None,
'io_log': [
# A bit convoluted but this is how we encode each chunk
# of IOLogRecord
[0.0, 'stdout', base64.standard_b64encode(
b'key: value'
).decode('ASCII')]
],
}]
}
helper = self.parameters.resume_cls([job], None, None)
session = SessionState([job])
# Ensure that the resource was not there initially
self.assertNotIn(job_id, session.resource_map)
# Process the representation data defined above
helper._process_job(session, jobs_repr, results_repr, job_id)
# Ensure that we now have the resource in the resource map
self.assertIn(job_id, session.resource_map)
# And that it looks right
self.assertEqual(
session.resource_map[job_id],
[Resource({'key': 'value'})])
def test_process_job_restores_jobs(self):
"""
verify that _process_job() recreates generated jobs
"""
# Set the stage for testing. Setup a session with a known local job,
# representation of the job (checksum) and representation of a single
# result, which has a trivial definition for a 'generated' job.
job_id = 'local'
job = make_job(id=job_id, plugin='local')
jobs_repr = {
job_id: job.checksum
}
results_repr = {
job_id: [{
'outcome': None,
'comments': None,
'execution_duration': None,
'return_code': None,
'io_log': [
[0.0, 'stdout', base64.standard_b64encode(
b'id: generated'
).decode('ASCII')],
[0.1, 'stdout', base64.standard_b64encode(
b'plugin: shell'
).decode('ASCII')],
[0.2, 'stdout', base64.standard_b64encode(
b'command: fake'
).decode('ASCII')]
],
}]
}
helper = self.parameters.resume_cls([job], None, None)
session = SessionState([job])
# Ensure that the 'generated' job was not there initially
self.assertNotIn('generated', session.job_state_map)
self.assertEqual(session.job_list, [job])
# Process the representation data defined above
helper._process_job(session, jobs_repr, results_repr, job_id)
# Ensure that we now have the 'generated' job in the job_state_map
self.assertIn('generated', session.job_state_map)
# And that it looks right
self.assertEqual(
session.job_state_map['generated'].job.id, 'generated')
self.assertIn(
session.job_state_map['generated'].job, session.job_list)
class SessionJobsAndResultsResumeTests(TestCaseWithParameters):
"""
Tests for :class:`~plainbox.impl.session.resume.SessionResumeHelper1`,
:class:`~plainbox.impl.session.resume.SessionResumeHelper2' and
:class:`~plainbox.impl.session.resume.SessionResumeHelper3' and how they
handle resume the session using _restore_SessionState_jobs_and_results()
method.
"""
parameter_names = ('resume_cls',)
parameter_values = ((SessionResumeHelper1,), (SessionResumeHelper2,),
(SessionResumeHelper3,), (SessionResumeHelper4,),
(SessionResumeHelper5,), (SessionResumeHelper6,))
def test_empty_session(self):
"""
verify that _restore_SessionState_jobs_and_results() works when
faced with a representation of an empty session. This is mostly
to do sanity checking on the 'easy' parts of the code before
testing specific cases in the rest of the code.
"""
session_repr = {
'jobs': {},
'results': {}
}
helper = self.parameters.resume_cls([], None, None)
session = SessionState([])
helper._restore_SessionState_jobs_and_results(session, session_repr)
self.assertEqual(session.job_list, [])
self.assertEqual(session.resource_map, {})
self.assertEqual(session.job_state_map, {})
def test_simple_session(self):
"""
verify that _restore_SessionState_jobs_and_results() works when
faced with a representation of a simple session (no generated jobs
or anything "exotic").
"""
job = make_job(id='job')
session_repr = {
'jobs': {
job.id: job.checksum,
},
'results': {
job.id: [{
'outcome': 'pass',
'comments': None,
'execution_duration': None,
'return_code': None,
'io_log': [],
}]
}
}
helper = self.parameters.resume_cls([], None, None)
session = SessionState([job])
helper._restore_SessionState_jobs_and_results(session, session_repr)
# Session still has one job in it
self.assertEqual(session.job_list, [job])
# Resources don't have anything (no resource jobs)
self.assertEqual(session.resource_map, {})
# The result was restored correctly. This is just a smoke test
# as specific tests for restoring results are written elsewhere
self.assertEqual(
session.job_state_map[job.id].result.outcome, 'pass')
def test_session_with_generated_jobs(self):
"""
verify that _restore_SessionState_jobs_and_results() works when
faced with a representation of a non-trivial session where one
job generates another one.
"""
parent = make_job(id='parent', plugin='local')
# The child job is only here so that we can get the checksum.
# We don't actually introduce it into the resume machinery
# caveat: make_job() has a default value for
# plugin='dummy' which we don't want here
child = make_job(id='child', plugin='shell', command='fake')
session_repr = {
'jobs': {
parent.id: parent.checksum,
child.id: child.checksum,
},
'results': {
parent.id: [{
'outcome': 'pass',
'comments': None,
'execution_duration': None,
'return_code': None,
'io_log': [
# This record will generate a job identical
# to the 'child' job defined above.
[0.0, 'stdout', base64.standard_b64encode(
b'id: child\n'
).decode('ASCII')],
[0.1, 'stdout', base64.standard_b64encode(
b'plugin: shell\n'
).decode('ASCII')],
[0.2, 'stdout', base64.standard_b64encode(
b'command: fake\n'
).decode('ASCII')]
],
}],
child.id: [],
}
}
# We only pass the parent to the helper! Child will be re-created
helper = self.parameters.resume_cls([parent], None, None)
session = SessionState([parent])
helper._restore_SessionState_jobs_and_results(session, session_repr)
# We should now have two jobs, parent and child
self.assertEqual(session.job_list, [parent, child])
# Resources don't have anything (no resource jobs)
self.assertEqual(session.resource_map, {})
def test_session_with_generated_jobs2(self):
"""
verify that _restore_SessionState_jobs_and_results() works when
faced with a representation of a non-trivial session where one
job generates another one and that one generates one more.
"""
# XXX: Important information about this test.
# This test uses a very subtle ordering of jobs to achieve
# the desired testing effect. This does not belong in this test case
# and should be split into a dedicated, very well documented method
# The only information I'll leave here now is that
# _restore_SessionState_jobs_and_results() is processing jobs
# in alphabetical order. This coupled with ordering:
# a_grandparent (generated)
# b_child (generated)
# c_parent
# creates the most pathological case possible.
parent = make_job(id='c_parent', plugin='local')
# The child job is only here so that we can get the checksum.
# We don't actually introduce it into the resume machinery
child = make_job(id='b_child', plugin='local', command='fake')
# caveat: make_job() has a default value for
# plugin='dummy' which we don't want here
grandchild = make_job(id='a_grandchild', plugin='shell',
command='fake')
session_repr = {
'jobs': {
parent.id: parent.checksum,
child.id: child.checksum,
grandchild.id: grandchild.checksum,
},
'results': {
parent.id: [{
'outcome': 'pass',
'comments': None,
'execution_duration': None,
'return_code': None,
'io_log': [
# This record will generate a job identical
# to the 'child' job defined above.
[0.0, 'stdout', base64.standard_b64encode(
b'id: b_child\n'
).decode('ASCII')],
[0.1, 'stdout', base64.standard_b64encode(
b'plugin: local\n'
).decode('ASCII')],
[0.2, 'stdout', base64.standard_b64encode(
b'command: fake\n'
).decode('ASCII')]
],
}],
child.id: [{
'outcome': 'pass',
'comments': None,
'execution_duration': None,
'return_code': None,
'io_log': [
# This record will generate a job identical
# to the 'child' job defined above.
[0.0, 'stdout', base64.standard_b64encode(
b'id: a_grandchild\n'
).decode('ASCII')],
[0.1, 'stdout', base64.standard_b64encode(
b'plugin: shell\n'
).decode('ASCII')],
[0.2, 'stdout', base64.standard_b64encode(
b'command: fake\n'
).decode('ASCII')]
],
}],
grandchild.id: [],
}
}
# We only pass the parent to the helper!
# The 'child' and 'grandchild' jobs will be re-created
helper = self.parameters.resume_cls([parent], None, None)
session = SessionState([parent])
helper._restore_SessionState_jobs_and_results(session, session_repr)
# We should now have two jobs, parent and child
self.assertEqual(session.job_list, [parent, child, grandchild])
# Resources don't have anything (no resource jobs)
self.assertEqual(session.resource_map, {})
def test_unknown_jobs_get_reported(self):
"""
verify that _restore_SessionState_jobs_and_results() reports
all unresolved jobs (as CorruptedSessionError exception)
"""
session_repr = {
'jobs': {
'job-id': 'job-checksum',
},
'results': {
'job-id': []
}
}
helper = self.parameters.resume_cls([], None, None)
session = SessionState([])
with self.assertRaises(CorruptedSessionError) as boom:
helper._restore_SessionState_jobs_and_results(
session, session_repr)
self.assertEqual(
str(boom.exception), "Unknown jobs remaining: job-id")
class SessionJobListResumeTests(TestCaseWithParameters):
"""
Tests for :class:`~plainbox.impl.session.resume.SessionResumeHelper1`,
:class:`~plainbox.impl.session.resume.SessionResumeHelper2' and
:class:`~plainbox.impl.session.resume.SessionResumeHelper3' and how they
handle resume session.job_list using _restore_SessionState_job_list()
method.
"""
parameter_names = ('resume_cls',)
parameter_values = ((SessionResumeHelper1,), (SessionResumeHelper2,),
(SessionResumeHelper3,), (SessionResumeHelper4,),
(SessionResumeHelper5,), (SessionResumeHelper6,))
def test_simple_session(self):
"""
verify that _restore_SessionState_job_list() does restore job_list
"""
job_a = make_job(id='a')
job_b = make_job(id='b')
session_repr = {
'jobs': {
job_a.id: job_a.checksum
},
'desired_job_list': [
job_a.id
],
'results': {
job_a.id: [],
}
}
helper = self.parameters.resume_cls([job_a, job_b], None, None)
session = SessionState([job_a, job_b])
helper._restore_SessionState_job_list(session, session_repr)
# Job "a" is still in the list but job "b" got removed
self.assertEqual(session.job_list, [job_a])
# The rest is tested by trim_job_list() tests
class RegressionTests(TestCase):
def test_1387782(self):
"""
https://bugs.launchpad.net/plainbox/+bug/1387782
"""
# This bug is about not being able to resume a session like this:
# - desired job list: [a]
# - run list [a_dep, a] (computed)
# - job_repr: [] # assume a_dep is not there
job_a = make_job(id='a', depends='a_dep')
job_a_dep = make_job(id='a_dep')
job_unrelated = make_job('unrelated')
session_repr = {
'version': 4,
'session': {
'jobs': {}, # nothing ran yet
'desired_job_list': [job_a.id], # we want a to run
'mandatory_job_list': [],
'results': {}, # nothing ran yet
},
}
helper = SessionResumeHelper4([job_a, job_a_dep, job_unrelated],
None, None)
# Mock away meta-data restore code as we're not testing that
with mock.patch.object(helper, '_restore_SessionState_metadata'):
session = helper.resume_json(session_repr)
# Both job_a and job_a_dep are there but job_unrelated is now gone
self.assertEqual(session.job_list, [job_a, job_a_dep])
def test_1388747(self):
"""
https://bugs.launchpad.net/plainbox/+bug/1388747
"""
# This bug is about not being able to resume a session like this:
# - job repr: a => a.checksum
# - desired job list, run list: [a]
# - results: (empty), no a there at all
job_a = make_job(id='a')
session_repr = {
'version': 4,
'session': {
'jobs': {
# a is about to run so it's mentioned in the checksum map
job_a.id: job_a.checksum
},
'desired_job_list': [job_a.id], # we want to run a
'mandatory_job_list': [],
'results': {}, # nothing ran yet
}
}
helper = SessionResumeHelper4([job_a], None, None)
# Mock away meta-data restore code as we're not testing that
with mock.patch.object(helper, '_restore_SessionState_metadata'):
session = helper.resume_json(session_repr)
# Both job_a has a default hollow result
self.assertTrue(session.job_state_map[job_a.id].result.is_hollow)
|