/usr/lib/python2.7/dist-packages/behave/model.py is in python-behave 1.2.5-2.
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 | # -*- coding: utf-8 -*-
from __future__ import absolute_import, with_statement, unicode_literals
from behave import step_registry
from behave.textutil import text as _text
import copy
import difflib
import itertools
import logging
import os.path
import six
from six.moves import zip
import sys
import time
import traceback
class Argument(object):
'''An argument found in a *feature file* step name and extracted using
step decorator `parameters`_.
The attributes are:
.. attribute:: original
The actual text matched in the step name.
.. attribute:: value
The potentially type-converted value of the argument.
.. attribute:: name
The name of the argument. This will be None if the parameter is
anonymous.
.. attribute:: start
The start index in the step name of the argument. Used for display.
.. attribute:: end
The end index in the step name of the argument. Used for display.
'''
def __init__(self, start, end, original, value, name=None):
self.start = start
self.end = end
self.original = original
self.value = value
self.name = name
# @total_ordering
# class FileLocation(unicode):
class FileLocation(object):
"""
Provides a value object for file location objects.
A file location consists of:
* filename
* line (number), optional
LOCATION SCHEMA:
* "{filename}:{line}" or
* "{filename}" (if line number is not present)
"""
# -- pylint: disable=R0904
# R0904: 30,0:FileLocation: Too many public methods (43/30) => unicode
__pychecker__ = "missingattrs=line" # -- Ignore warnings for 'line'.
def __init__(self, filename, line=None):
self.filename = filename
self.line = line
def get(self):
return self.filename
def abspath(self):
return os.path.abspath(self.filename)
def basename(self):
return os.path.basename(self.filename)
def dirname(self):
return os.path.dirname(self.filename)
def relpath(self, start=os.curdir):
"""
Compute relative path for start to filename.
:param start: Base path or start directory (default=current dir).
:return: Relative path from start to filename
"""
return os.path.relpath(self.filename, start)
def exists(self):
return os.path.exists(self.filename)
def _line_lessthan(self, other_line):
if self.line is None:
return not (other_line is None)
elif other_line is None:
return False
else:
return self.line < other_line
def __eq__(self, other):
if isinstance(other, FileLocation):
return self.filename == other.filename and self.line == other.line
elif isinstance(other, six.string_types):
return self.filename == other
else:
raise AttributeError("Cannot compare FileLocation with %s:%s" % \
(type(other), other))
def __ne__(self, other):
return not self == other
def __lt__(self, other):
if isinstance(other, FileLocation):
if self.filename < other.filename:
return True
elif self.filename > other.filename:
return False
else:
assert self.filename == other.filename
return self._line_lessthan(other.line)
elif isinstance(other, six.string_types):
return self.filename < other
else:
raise AttributeError("Cannot compare FileLocation with %s:%s" % \
(type(other), other))
def __le__(self, other):
# -- SEE ALSO: python2.7, functools.total_ordering
return not other < self
def __gt__(self, other):
# -- SEE ALSO: python2.7, functools.total_ordering
if isinstance(other, FileLocation):
return other < self
else:
return self.filename > other
def __ge__(self, other):
# -- SEE ALSO: python2.7, functools.total_ordering
return not self < other
def __repr__(self):
return u'<FileLocation: filename="%s", line=%s>' % \
(self.filename, self.line)
def __str__(self):
filename = self.filename
if isinstance(filename, six.binary_type):
filename = _text(filename, "utf-8")
if self.line is None:
return filename
return u"%s:%d" % (filename, self.line)
if six.PY2:
__unicode__ = __str__
__str__ = lambda self: self.__unicode__().encode("utf-8")
class BasicStatement(object):
def __init__(self, filename, line, keyword, name):
filename = filename or '<string>'
filename = os.path.relpath(filename, os.getcwd()) # -- NEEDS: abspath?
self.location = FileLocation(filename, line)
assert isinstance(keyword, six.text_type)
assert isinstance(name, six.text_type)
self.keyword = keyword
self.name = name
@property
def filename(self):
# return os.path.abspath(self.location.filename)
return self.location.filename
@property
def line(self):
return self.location.line
# @property
# def location(self):
# p = os.path.relpath(self.filename, os.getcwd())
# return '%s:%d' % (p, self.line)
def __hash__(self):
# -- NEEDED-FOR: PYTHON3
# return id((self.keyword, self.name))
return id(self)
def __eq__(self, other):
# -- PYTHON3 SUPPORT, ORDERABLE:
# NOTE: Ignore potential FileLocation differences.
return (self.keyword, self.name) == (other.keyword, other.name)
def __lt__(self, other):
# -- PYTHON3 SUPPORT, ORDERABLE:
# NOTE: Ignore potential FileLocation differences.
return (self.keyword, self.name) < (other.keyword, other.name)
def __ne__(self, other):
return not self.__eq__(other)
def __le__(self, other):
# -- SEE ALSO: python2.7, functools.total_ordering
return not other < self
def __gt__(self, other):
# -- SEE ALSO: python2.7, functools.total_ordering
assert isinstance(other, BasicStatement)
return other < self
def __ge__(self, other):
# -- SEE ALSO: python2.7, functools.total_ordering
return not self < other
# def __cmp__(self, other):
# # -- NOTE: Ignore potential FileLocation differences.
# return cmp((self.keyword, self.name), (other.keyword, other.name))
class TagStatement(BasicStatement):
def __init__(self, filename, line, keyword, name, tags):
super(TagStatement, self).__init__(filename, line, keyword, name)
self.tags = tags
class TagAndStatusStatement(BasicStatement):
final_status = ('passed', 'failed', 'skipped')
def __init__(self, filename, line, keyword, name, tags):
super(TagAndStatusStatement, self).__init__(filename, line, keyword, name)
self.tags = tags
self.should_skip = False
self.skip_reason = None
self._cached_status = None
@property
def status(self):
if self._cached_status not in self.final_status:
# -- RECOMPUTE: As long as final status is not reached.
self._cached_status = self.compute_status()
return self._cached_status
def reset(self):
self.should_skip = False
self.skip_reason = None
self._cached_status = None
def compute_status(self):
raise NotImplementedError
class Replayable(object):
type = None
def replay(self, formatter):
getattr(formatter, self.type)(self)
class Feature(TagAndStatusStatement, Replayable):
'''A `feature`_ parsed from a *feature file*.
The attributes are:
.. attribute:: keyword
This is the keyword as seen in the *feature file*. In English this will
be "Feature".
.. attribute:: name
The name of the feature (the text after "Feature".)
.. attribute:: description
The description of the feature as seen in the *feature file*. This is
stored as a list of text lines.
.. attribute:: background
The :class:`~behave.model.Background` for this feature, if any.
.. attribute:: scenarios
A list of :class:`~behave.model.Scenario` making up this feature.
.. attribute:: tags
A list of @tags (as :class:`~behave.model.Tag` which are basically
glorified strings) attached to the feature.
See :ref:`controlling things with tags`.
.. attribute:: status
Read-Only. A summary status of the feature's run. If read before the
feature is fully tested it will return "untested" otherwise it will
return one of:
"untested"
The feature was has not been completely tested yet.
"skipped"
One or more steps of this feature was passed over during testing.
"passed"
The feature was tested successfully.
"failed"
One or more steps of this feature failed.
.. attribute:: duration
The time, in seconds, that it took to test this feature. If read before
the feature is tested it will return 0.0.
.. attribute:: filename
The file name (or "<string>") of the *feature file* where the feature
was found.
.. attribute:: line
The line number of the *feature file* where the feature was found.
.. _`feature`: gherkin.html#features
'''
type = "feature"
def __init__(self, filename, line, keyword, name, tags=None,
description=None, scenarios=None, background=None):
tags = tags or []
super(Feature, self).__init__(filename, line, keyword, name, tags)
self.description = description or []
self.scenarios = []
self.background = background
self.parser = None
if scenarios:
for scenario in scenarios:
self.add_scenario(scenario)
def reset(self):
'''
Reset to clean state before a test run.
'''
super(Feature, self).reset()
for scenario in self.scenarios:
scenario.reset()
def __repr__(self):
return '<Feature "%s": %d scenario(s)>' % \
(self.name, len(self.scenarios))
def __iter__(self):
return iter(self.scenarios)
def add_scenario(self, scenario):
scenario.feature = self
scenario.background = self.background
self.scenarios.append(scenario)
def compute_status(self):
"""
Compute the status of this feature based on its:
* scenarios
* scenario outlines
:return: Computed status (as string-enum).
"""
skipped = True
passed_count = 0
for scenario in self.scenarios:
scenario_status = scenario.status
if scenario_status == 'failed':
return 'failed'
elif scenario_status == 'untested':
if passed_count > 0:
return 'failed' # ABORTED: Some passed, now untested.
return 'untested'
if scenario_status != 'skipped':
skipped = False
if scenario_status == 'passed':
passed_count += 1
return skipped and 'skipped' or 'passed'
@property
def duration(self):
# -- NEW: Background is executed N times, now part of scenarios.
feature_duration = 0.0
for scenario in self.scenarios:
feature_duration += scenario.duration
return feature_duration
def walk_scenarios(self, with_outlines=False):
"""
Provides a flat list of all scenarios of this feature.
A ScenarioOutline element adds its scenarios to this list.
But the ScenarioOutline element itself is only added when specified.
A flat scenario list is useful when all scenarios of a features
should be processed.
:param with_outlines: If ScenarioOutline items should be added, too.
:return: List of all scenarios of this feature.
"""
all_scenarios = []
for scenario in self.scenarios:
if isinstance(scenario, ScenarioOutline):
scenario_outline = scenario
if with_outlines:
all_scenarios.append(scenario_outline)
all_scenarios.extend(scenario_outline.scenarios)
else:
all_scenarios.append(scenario)
return all_scenarios
def should_run(self, config=None):
"""
Determines if this Feature (and its scenarios) should run.
Implements the run decision logic for a feature.
The decision depends on:
* if the Feature is marked as skipped
* if the config.tags (tag expression) enable/disable this feature
:param config: Runner configuration to use (optional).
:return: True, if scenario should run. False, otherwise.
"""
answer = not self.should_skip
if answer and config:
answer = self.should_run_with_tags(config.tags)
return answer
def should_run_with_tags(self, tag_expression):
'''
Determines if this feature should run when the tag expression is used.
A feature should run if:
* it should run according to its tags
* any of its scenarios should run according to its tags
:param tag_expression: Runner/config environment tags to use.
:return: True, if feature should run. False, otherwise (skip it).
'''
run_feature = tag_expression.check(self.tags)
if not run_feature:
for scenario in self:
if scenario.should_run_with_tags(tag_expression):
run_feature = True
break
return run_feature
def mark_skipped(self):
"""Marks this feature (and all its scenarios and steps) as skipped.
Note this function may be called before the feature is executed.
"""
self.skip(require_not_executed=True)
assert self.status == "skipped"
def skip(self, reason=None, require_not_executed=False):
"""Skip executing this feature or the remaining parts of it.
Note that this feature may be already partly executed
when this function is called.
:param reason: Optional reason why feature should be skipped (as string).
:param require_not_executed: Optional, requires that feature is not
executed yet (default: false).
"""
if reason:
logger = logging.getLogger("behave")
logger.warn(u"SKIP FEATURE %s: %s" % (self.name, reason))
self._cached_status = None
self.should_skip = True
self.skip_reason = reason
for scenario in self.scenarios:
scenario.skip(reason, require_not_executed)
if not self.scenarios:
# -- SPECIAL CASE: Feature without scenarios
self._cached_status = "skipped"
assert self.status in self.final_status #< skipped, failed or passed.
def run(self, runner):
self._cached_status = None
runner.context._push()
runner.context.feature = self
# run this feature if the tags say so or any one of its scenarios
run_feature = self.should_run(runner.config)
if run_feature or runner.config.show_skipped:
for formatter in runner.formatters:
formatter.feature(self)
# current tags as a set
runner.context.tags = set(self.tags)
hooks_called = False
if not runner.config.dry_run and run_feature:
hooks_called = True
for tag in self.tags:
runner.run_hook('before_tag', runner.context, tag)
runner.run_hook('before_feature', runner.context, self)
# -- RE-EVALUATE SHOULD-RUN STATE:
# Hook may call feature.mark_skipped() to exclude it.
run_feature = self.should_run()
if self.background and (run_feature or runner.config.show_skipped):
for formatter in runner.formatters:
formatter.background(self.background)
failed_count = 0
for scenario in self.scenarios:
# -- OPTIONAL: Select scenario by name (regular expressions).
if (runner.config.name and
not scenario.should_run_with_name_select(runner.config)):
scenario.mark_skipped()
continue
failed = scenario.run(runner)
if failed:
failed_count += 1
if runner.config.stop or runner.aborted:
# -- FAIL-EARLY: Stop after first failure.
break
if not self.scenarios and not run_feature:
# -- SPECIAL CASE: Feature without scenarios
self._cached_status = 'skipped'
if hooks_called:
runner.run_hook('after_feature', runner.context, self)
for tag in self.tags:
runner.run_hook('after_tag', runner.context, tag)
runner.context._pop()
if run_feature or runner.config.show_skipped:
for formatter in runner.formatters:
formatter.eof()
failed = (failed_count > 0)
return failed
class Background(BasicStatement, Replayable):
'''A `background`_ parsed from a *feature file*.
The attributes are:
.. attribute:: keyword
This is the keyword as seen in the *feature file*. In English this will
typically be "Background".
.. attribute:: name
The name of the background (the text after "Background:".)
.. attribute:: steps
A list of :class:`~behave.model.Step` making up this background.
.. attribute:: duration
The time, in seconds, that it took to run this background. If read
before the background is run it will return 0.0.
.. attribute:: filename
The file name (or "<string>") of the *feature file* where the background
was found.
.. attribute:: line
The line number of the *feature file* where the background was found.
.. _`background`: gherkin.html#backgrounds
'''
type = "background"
def __init__(self, filename, line, keyword, name, steps=None):
super(Background, self).__init__(filename, line, keyword, name)
self.steps = steps or []
def __repr__(self):
return '<Background "%s">' % self.name
def __iter__(self):
return iter(self.steps)
@property
def duration(self):
duration = 0
for step in self.steps:
duration += step.duration
return duration
class Scenario(TagAndStatusStatement, Replayable):
'''A `scenario`_ parsed from a *feature file*.
The attributes are:
.. attribute:: keyword
This is the keyword as seen in the *feature file*. In English this will
typically be "Scenario".
.. attribute:: name
The name of the scenario (the text after "Scenario:".)
.. attribute:: description
The description of the scenario as seen in the *feature file*.
This is stored as a list of text lines.
.. attribute:: feature
The :class:`~behave.model.Feature` this scenario belongs to.
.. attribute:: steps
A list of :class:`~behave.model.Step` making up this scenario.
.. attribute:: tags
A list of @tags (as :class:`~behave.model.Tag` which are basically
glorified strings) attached to the scenario.
See :ref:`controlling things with tags`.
.. attribute:: status
Read-Only. A summary status of the scenario's run. If read before the
scenario is fully tested it will return "untested" otherwise it will
return one of:
"untested"
The scenario was has not been completely tested yet.
"skipped"
One or more steps of this scenario was passed over during testing.
"passed"
The scenario was tested successfully.
"failed"
One or more steps of this scenario failed.
.. attribute:: duration
The time, in seconds, that it took to test this scenario. If read before
the scenario is tested it will return 0.0.
.. attribute:: filename
The file name (or "<string>") of the *feature file* where the scenario
was found.
.. attribute:: line
The line number of the *feature file* where the scenario was found.
.. _`scenario`: gherkin.html#scenarios
'''
type = "scenario"
def __init__(self, filename, line, keyword, name, tags=None, steps=None,
description=None):
tags = tags or []
super(Scenario, self).__init__(filename, line, keyword, name, tags)
self.description = description or []
self.steps = steps or []
self.background = None
self.feature = None # REFER-TO: owner=Feature
self._background_steps = None
self._row = None
self.was_dry_run = False
self.stderr = None
self.stdout = None
def reset(self):
'''
Reset the internal data to reintroduce new-born state just after the
ctor was called.
'''
super(Scenario, self).reset()
self._row = None
self.was_dry_run = False
self.stderr = None
self.stdout = None
for step in self.all_steps:
step.reset()
@property
def background_steps(self):
'''
Provide background steps if feature has a background.
Lazy init that copies the background steps.
Note that a copy of the background steps is needed to ensure
that the background step status is specific to the scenario.
:return: List of background steps or empty list
'''
if self._background_steps is None:
# -- LAZY-INIT (need copy of background.steps):
# Each scenario needs own background.steps status.
# Otherwise, background step status of the last scenario is used.
steps = []
if self.background:
steps = [copy.copy(step) for step in self.background.steps]
self._background_steps = steps
return self._background_steps
@property
def all_steps(self):
"""Returns iterator to all steps, including background steps if any."""
if self.background is not None:
return itertools.chain(self.background_steps, self.steps)
else:
return iter(self.steps)
def __repr__(self):
return '<Scenario "%s">' % self.name
def __iter__(self):
return self.all_steps
def compute_status(self):
"""Compute the status of the scenario from its steps.
:return: Computed status (as string).
"""
for step in self.all_steps:
if step.status == 'undefined':
if self.was_dry_run:
# -- SPECIAL CASE: In dry-run with undefined-step discovery
# Undefined steps should not cause failed scenario.
return 'untested'
else:
# -- NORMALLY: Undefined steps cause failed scenario.
return 'failed'
elif step.status != 'passed':
assert step.status in ('failed', 'skipped', 'untested')
return step.status
#elif step.status == 'failed':
# return 'failed'
#elif step.status == 'skipped':
# return 'skipped'
#elif step.status == 'untested':
# return 'untested'
return 'passed'
@property
def duration(self):
# -- ORIG: for step in self.steps: Background steps were excluded.
scenario_duration = 0
for step in self.all_steps:
scenario_duration += step.duration
return scenario_duration
@property
def effective_tags(self):
"""
Effective tags for this scenario:
* own tags
* tags inherited from its feature
"""
tags = self.tags
if self.feature:
tags = self.feature.tags + self.tags
return tags
def should_run(self, config=None):
"""
Determines if this Scenario (or ScenarioOutline) should run.
Implements the run decision logic for a scenario.
The decision depends on:
* if the Scenario is marked as skipped
* if the config.tags (tag expression) enable/disable this scenario
* if the scenario is selected by name
:param config: Runner configuration to use (optional).
:return: True, if scenario should run. False, otherwise.
"""
answer = not self.should_skip
if answer and config:
answer = (self.should_run_with_tags(config.tags) and
self.should_run_with_name_select(config))
return answer
def should_run_with_tags(self, tag_expression):
"""
Determines if this scenario should run when the tag expression is used.
:param tag_expression: Runner/config environment tags to use.
:return: True, if scenario should run. False, otherwise (skip it).
"""
return tag_expression.check(self.effective_tags)
def should_run_with_name_select(self, config):
"""Determines if this scenario should run when it is selected by name.
:param config: Runner/config environment name regexp (if any).
:return: True, if scenario should run. False, otherwise (skip it).
"""
# -- SELECT-ANY: If select by name is not specified (not config.name).
return not config.name or config.name_re.search(self.name)
def mark_skipped(self):
"""Marks this scenario (and all its steps) as skipped.
Note that this method can be called before the scenario is executed.
"""
self.skip(require_not_executed=True)
assert self.status == "skipped", "OOPS: scenario.status=%s" % self.status
def skip(self, reason=None, require_not_executed=False):
"""Skip from executing this scenario or the remaining parts of it.
Note that the scenario may be already partly executed
when this method is called.
:param reason: Optional reason why it should be skipped (as string).
"""
if reason:
scenario_type = self.__class__.__name__
logger = logging.getLogger("behave")
logger.warn(u"SKIP %s %s: %s" % (scenario_type, self.name, reason))
self._cached_status = None
self.should_skip = True
self.skip_reason = reason
for step in self.all_steps:
not_executed = step.status in ("untested", "skipped")
if not_executed:
step.status = "skipped"
else:
assert not require_not_executed, \
"REQUIRE NOT-EXECUTED, but step is %s" % step.status
if not self.all_steps:
# -- SPECIAL CASE: Scenario without steps
self._cached_status = "skipped"
assert self.status in self.final_status #< skipped, failed or passed
def run(self, runner):
self._cached_status = None
failed = False
run_scenario = self.should_run(runner.config)
run_steps = run_scenario and not runner.config.dry_run
dry_run_scenario = run_scenario and runner.config.dry_run
self.was_dry_run = dry_run_scenario
if run_scenario or runner.config.show_skipped:
for formatter in runner.formatters:
formatter.scenario(self)
runner.context._push()
runner.context.scenario = self
runner.context.tags = set(self.effective_tags)
hooks_called = False
if not runner.config.dry_run and run_scenario:
hooks_called = True
for tag in self.tags:
runner.run_hook('before_tag', runner.context, tag)
runner.run_hook('before_scenario', runner.context, self)
# -- RE-EVALUATE SHOULD-RUN STATE:
# Hook may call scenario.mark_skipped() to exclude it.
run_scenario = run_steps = self.should_run()
runner.setup_capture()
if run_scenario or runner.config.show_skipped:
for step in self:
for formatter in runner.formatters:
formatter.step(step)
for step in self.all_steps:
if run_steps:
if not step.run(runner):
run_steps = False
failed = True
runner.context._set_root_attribute('failed', True)
self._cached_status = 'failed'
elif self.should_skip:
# -- CASE: Step skipped remaining scenario.
# assert self.status == "skipped", "Status: %s" % self.status
run_steps = False
elif failed or dry_run_scenario:
# -- SKIP STEPS: After failure/undefined-step occurred.
# BUT: Detect all remaining undefined steps.
step.status = 'skipped'
if dry_run_scenario:
step.status = 'untested'
found_step = step_registry.registry.find_match(step)
if not found_step:
step.status = 'undefined'
runner.undefined_steps.append(step)
else:
# -- SKIP STEPS: For disabled scenario.
# CASES:
# * Undefined steps are not detected (by intention).
# * Step skipped remaining scenario.
step.status = 'skipped'
if not run_scenario:
# -- SPECIAL CASE: Scenario without steps.
self._cached_status = 'skipped'
# Attach the stdout and stderr if generate Junit report
if runner.config.junit:
self.stdout = runner.context.stdout_capture.getvalue()
self.stderr = runner.context.stderr_capture.getvalue()
runner.teardown_capture()
if hooks_called:
runner.run_hook('after_scenario', runner.context, self)
for tag in self.tags:
runner.run_hook('after_tag', runner.context, tag)
runner.context._pop()
return failed
class ScenarioOutlineBuilder(object):
"""Helper class to use a ScenarioOutline as a template and
build its scenarios (as template instances).
"""
def __init__(self, annotation_schema):
self.annotation_schema = annotation_schema
@staticmethod
def render_template(text, row=None, params=None):
"""Render a text template with placeholders, ala "Hello <name>".
:param row: As placeholder provider (dict-like).
:param params: As additional placeholder provider (as dict).
:return: Rendered text, known placeholders are substituted w/ values.
"""
if not ('<' in text and '>' in text):
return text
safe_values = False
for placeholders in (row, params):
if not placeholders:
continue
for name, value in placeholders.items():
if safe_values and ('<' in value and '>' in value):
continue # -- OOPS, value looks like placeholder.
text = text.replace("<%s>" % name, value)
return text
def make_scenario_name(self, outline_name, example, row, params=None):
"""Build a scenario name for an example row of this scenario outline.
Placeholders for row data are replaced by values.
SCHEMA: "{outline_name} -*- {examples.name}@{row.id}"
:param outline_name: ScenarioOutline's name (as template).
:param example: Examples object.
:param row: Row of this example.
:param params: Additional placeholders for example/row.
:return: Computed name for the scenario representing example/row.
"""
if params is None:
params = {}
params["examples.name"] = example.name or ""
params.setdefault("examples.index", example.index)
params.setdefault("row.index", row.index)
params.setdefault("row.id", row.id)
# -- STEP: Replace placeholders in scenario/example name (if any).
examples_name = self.render_template(example.name, row, params)
params["examples.name"] = examples_name
scenario_name = self.render_template(outline_name, row, params)
class Data(object):
def __init__(self, name, index):
self.name = name
self.index = index
self.id = name
example_data = Data(examples_name, example.index)
row_data = Data(row.id, row.index)
return self.annotation_schema.format(name=scenario_name,
examples=example_data, row=row_data)
@classmethod
def make_row_tags(cls, outline_tags, row, params=None):
if not outline_tags:
return None
tags = []
for tag in outline_tags:
if '<' in tag and '>' in tag:
tag = cls.render_template(tag, row, params)
if '<' in tag or '>' in tag:
# -- OOPS: Unknown placeholder, drop tag.
continue
new_tag = Tag.make_name(tag, unescape=True)
tags.append(new_tag)
return tags
@classmethod
def make_step_for_row(cls, outline_step, row, params=None):
# -- BASED-ON: new_step = outline_step.set_values(row)
new_step = copy.deepcopy(outline_step)
new_step.name = cls.render_template(new_step.name, row, params)
if new_step.text:
new_step.text = cls.render_template(new_step.text, row)
if new_step.table:
for name, value in row.items():
for row in new_step.table:
for i, cell in enumerate(row.cells):
row.cells[i] = cell.replace("<%s>" % name, value)
return new_step
def build_scenarios(self, scenario_outline):
"""Build scenarios for a ScenarioOutline from its examples."""
# -- BUILD SCENARIOS (once): For this ScenarioOutline from examples.
params = {
"examples.name": None,
"examples.index": None,
"row.index": None,
"row.id": None,
}
scenarios = []
for example_index, example in enumerate(scenario_outline.examples):
example.index = example_index+1
params["examples.name"] = example.name
params["examples.index"] = _text(example.index)
for row_index, row in enumerate(example.table):
row.index = row_index+1
row.id = "%d.%d" % (example.index, row.index)
params["row.id"] = row.id
params["row.index"] = _text(row.index)
scenario_name = self.make_scenario_name(scenario_outline.name,
example, row, params)
row_tags = self.make_row_tags(scenario_outline.tags, row, params)
new_steps = []
for outline_step in scenario_outline.steps:
new_step = self.make_step_for_row(outline_step, row, params)
new_steps.append(new_step)
# -- STEP: Make Scenario name for this row.
# scenario_line = example.line + 2 + row_index
scenario_line = row.line
scenario = Scenario(scenario_outline.filename, scenario_line,
scenario_outline.keyword,
scenario_name, row_tags, new_steps)
scenario.feature = scenario_outline.feature
scenario.background = scenario_outline.background
scenario._row = row
scenarios.append(scenario)
return scenarios
class ScenarioOutline(Scenario):
"""A `scenario outline`_ parsed from a *feature file*.
A scenario outline extends the existing :class:`~behave.model.Scenario`
class with the addition of the :class:`~behave.model.Examples` tables of
data from the *feature file*.
The attributes are:
.. attribute:: keyword
This is the keyword as seen in the *feature file*. In English this will
typically be "Scenario Outline".
.. attribute:: name
The name of the scenario (the text after "Scenario Outline:".)
.. attribute:: description
The description of the `scenario outline`_ as seen in the *feature file*.
This is stored as a list of text lines.
.. attribute:: feature
The :class:`~behave.model.Feature` this scenario outline belongs to.
.. attribute:: steps
A list of :class:`~behave.model.Step` making up this scenario outline.
.. attribute:: examples
A list of :class:`~behave.model.Examples` used by this scenario outline.
.. attribute:: tags
A list of @tags (as :class:`~behave.model.Tag` which are basically
glorified strings) attached to the scenario.
See :ref:`controlling things with tags`.
.. attribute:: status
Read-Only. A summary status of the scenario outlines's run. If read
before the scenario is fully tested it will return "untested" otherwise
it will return one of:
"untested"
The scenario was has not been completely tested yet.
"skipped"
One or more scenarios of this outline was passed over during testing.
"passed"
The scenario was tested successfully.
"failed"
One or more scenarios of this outline failed.
.. attribute:: duration
The time, in seconds, that it took to test the scenarios of this
outline. If read before the scenarios are tested it will return 0.0.
.. attribute:: filename
The file name (or "<string>") of the *feature file* where the scenario
was found.
.. attribute:: line
The line number of the *feature file* where the scenario was found.
.. _`scenario outline`: gherkin.html#scenario-outlines
"""
type = "scenario_outline"
annotation_schema = u"{name} -- @{row.id} {examples.name}"
def __init__(self, filename, line, keyword, name, tags=None,
steps=None, examples=None, description=None):
super(ScenarioOutline, self).__init__(filename, line, keyword, name,
tags, steps, description)
self.examples = examples or []
self._scenarios = []
def reset(self):
"""Reset runtime temporary data like before a test run."""
super(ScenarioOutline, self).reset()
for scenario in self._scenarios: # -- AVOID: BUILD-SCENARIOS
scenario.reset()
@property
def scenarios(self):
"""Return the scenarios with the steps altered to take the values from
the examples.
"""
if self._scenarios:
return self._scenarios
# -- BUILD SCENARIOS (once): For this ScenarioOutline from examples.
builder = ScenarioOutlineBuilder(self.annotation_schema)
self._scenarios = builder.build_scenarios(self)
return self._scenarios
def __repr__(self):
return '<ScenarioOutline "%s">' % self.name
def __iter__(self):
return iter(self.scenarios) # -- REQUIRE: BUILD-SCENARIOS
def compute_status(self):
skipped_count = 0
for scenario in self._scenarios: # -- AVOID: BUILD-SCENARIOS
scenario_status = scenario.status
if scenario_status in ("failed", "untested"):
return scenario_status
elif scenario_status == "skipped":
skipped_count += 1
if skipped_count == len(self._scenarios):
# -- ALL SKIPPED:
return "skipped"
# -- OTHERWISE: ALL PASSED
return "passed"
@property
def duration(self):
outline_duration = 0
for scenario in self._scenarios: # -- AVOID: BUILD-SCENARIOS
outline_duration += scenario.duration
return outline_duration
def should_run_with_tags(self, tag_expression):
"""
Determines if this scenario outline (or one of its scenarios)
should run when the tag expression is used.
:param tag_expression: Runner/config environment tags to use.
:return: True, if scenario should run. False, otherwise (skip it).
"""
if tag_expression.check(self.effective_tags):
return True
for scenario in self.scenarios: # -- REQUIRE: BUILD-SCENARIOS
if scenario.should_run_with_tags(tag_expression):
return True
# -- NOTHING SELECTED:
return False
def should_run_with_name_select(self, config):
"""Determines if this scenario should run when it is selected by name.
:param config: Runner/config environment name regexp (if any).
:return: True, if scenario should run. False, otherwise (skip it).
"""
if not config.name:
return True # -- SELECT-ALL: Select by name is not specified.
for scenario in self.scenarios: # -- REQUIRE: BUILD-SCENARIOS
if scenario.should_run_with_name_select(config):
return True
# -- NOTHING SELECTED:
return False
def mark_skipped(self):
"""Marks this scenario outline (and all its scenarios/steps) as skipped.
Note that this method may be called before the scenario outline
is executed.
"""
self.skip(require_not_executed=True)
assert self.status == "skipped"
def skip(self, reason=None, require_not_executed=False):
"""Skip from executing this scenario outline or its remaining parts.
Note that the scenario outline may be already partly executed
when this method is called.
:param reason: Optional reason why it should be skipped (as string).
"""
if reason:
logger = logging.getLogger("behave")
logger.warn(u"SKIP ScenarioOutline %s: %s" % (self.name, reason))
self._cached_status = None
self.should_skip = True
for scenario in self.scenarios:
scenario.skip(reason, require_not_executed)
if not self.scenarios:
# -- SPECIAL CASE: ScenarioOutline without scenarios/examples
self._cached_status = "skipped"
assert self.status in self.final_status #< skipped, failed or passed
def run(self, runner):
self._cached_status = None
failed_count = 0
for scenario in self.scenarios: # -- REQUIRE: BUILD-SCENARIOS
runner.context._set_root_attribute('active_outline', scenario._row)
failed = scenario.run(runner)
if failed:
failed_count += 1
if runner.config.stop or runner.aborted:
# -- FAIL-EARLY: Stop after first failure.
break
runner.context._set_root_attribute('active_outline', None)
return failed_count > 0
class Examples(BasicStatement, Replayable):
'''A table parsed from a `scenario outline`_ in a *feature file*.
The attributes are:
.. attribute:: keyword
This is the keyword as seen in the *feature file*. In English this will
typically be "Example".
.. attribute:: name
The name of the example (the text after "Example:".)
.. attribute:: table
An instance of :class:`~behave.model.Table` that came with the example
in the *feature file*.
.. attribute:: filename
The file name (or "<string>") of the *feature file* where the example
was found.
.. attribute:: line
The line number of the *feature file* where the example was found.
.. _`examples`: gherkin.html#examples
'''
type = "examples"
def __init__(self, filename, line, keyword, name, table=None):
super(Examples, self).__init__(filename, line, keyword, name)
self.table = table
self.index = None
class Step(BasicStatement, Replayable):
'''A single `step`_ parsed from a *feature file*.
The attributes are:
.. attribute:: keyword
This is the keyword as seen in the *feature file*. In English this will
typically be "Given", "When", "Then" or a number of other words.
.. attribute:: name
The name of the step (the text after "Given" etc.)
.. attribute:: step_type
The type of step as determined by the keyword. If the keyword is "and"
then the previous keyword in the *feature file* will determine this
step's step_type.
.. attribute:: text
An instance of :class:`~behave.model.Text` that came with the step
in the *feature file*.
.. attribute:: table
An instance of :class:`~behave.model.Table` that came with the step
in the *feature file*.
.. attribute:: status
Read-Only. A summary status of the step's run. If read before the
step is tested it will return "untested" otherwise it will
return one of:
"skipped"
This step was passed over during testing.
"passed"
The step was tested successfully.
"failed"
The step failed.
.. attribute:: duration
The time, in seconds, that it took to test this step. If read before the
step is tested it will return 0.0.
.. attribute:: error_message
If the step failed then this will hold any error information, as a
single string. It will otherwise be None.
.. attribute:: filename
The file name (or "<string>") of the *feature file* where the step was
found.
.. attribute:: line
The line number of the *feature file* where the step was found.
.. _`step`: gherkin.html#steps
'''
type = "step"
def __init__(self, filename, line, keyword, step_type, name, text=None,
table=None):
super(Step, self).__init__(filename, line, keyword, name)
self.step_type = step_type
self.text = text
self.table = table
self.status = 'untested'
self.duration = 0
self.exception = None
self.exc_traceback = None
self.error_message = None
def reset(self):
'''Reset temporary runtime data to reach clean state again.'''
self.status = 'untested'
self.duration = 0
self.exception = None
self.exc_traceback = None
self.error_message = None
def store_exception_context(self, exception):
self.exception = exception
self.exc_traceback = sys.exc_info()[2]
def __repr__(self):
return '<%s "%s">' % (self.step_type, self.name)
def __eq__(self, other):
return (self.step_type, self.name) == (other.step_type, other.name)
def __hash__(self):
return hash(self.step_type) + hash(self.name)
def set_values(self, table_row):
"""Clone a new step from this one, used for ScenarioOutline.
Replace ScenarioOutline placeholders w/ values.
:param table_row: Placeholder data for example row.
:return: Cloned, adapted step object.
.. note:: Deprecating
Use 'ScenarioOutlineBuilder.make_step_for_row()' instead.
"""
import warnings
warnings.warn("Use 'ScenarioOutline.make_step_for_row()' instead",
PendingDeprecationWarning, stacklevel=2)
outline_step = self
return ScenarioOutlineBuilder.make_step_for_row(outline_step, table_row)
def run(self, runner, quiet=False, capture=True):
# -- RESET: Run information.
self.exception = self.exc_traceback = self.error_message = None
self.status = 'untested'
# access module var here to allow test mocking to work
match = step_registry.registry.find_match(self)
if match is None:
runner.undefined_steps.append(self)
if not quiet:
for formatter in runner.formatters:
formatter.match(NoMatch())
self.status = 'undefined'
if not quiet:
for formatter in runner.formatters:
formatter.result(self)
return False
keep_going = True
if not quiet:
for formatter in runner.formatters:
formatter.match(match)
runner.run_hook('before_step', runner.context, self)
if capture:
runner.start_capture()
try:
start = time.time()
# -- ENSURE:
# * runner.context.text/.table attributes are reset (#66).
# * Even EMPTY multiline text is available in context.
runner.context.text = self.text
runner.context.table = self.table
match.run(runner.context)
if self.status == 'untested':
# -- NOTE: Executed step may have skipped scenario and itself.
self.status = 'passed'
except KeyboardInterrupt as e:
runner.aborted = True
error = u"ABORTED: By user (KeyboardInterrupt)."
self.status = 'failed'
self.store_exception_context(e)
except AssertionError as e:
self.status = 'failed'
self.store_exception_context(e)
if e.args:
message = _text(e)
error = u'Assertion Failed: '+ message
else:
# no assertion text; format the exception
error = _text(traceback.format_exc())
except Exception as e:
self.status = 'failed'
error = _text(traceback.format_exc())
self.store_exception_context(e)
self.duration = time.time() - start
if capture:
runner.stop_capture()
# flesh out the failure with details
if self.status == 'failed':
assert isinstance(error, six.text_type)
if capture:
# -- CAPTURE-ONLY: Non-nested step failures.
if runner.config.stdout_capture:
output = runner.stdout_capture.getvalue()
if output:
output = _text(output)
error += u'\nCaptured stdout:\n' + output
if runner.config.stderr_capture:
output = runner.stderr_capture.getvalue()
if output:
output = _text(output)
error += u'\nCaptured stderr:\n' + output
if runner.config.log_capture:
output = runner.log_capture.getvalue()
if output:
output = _text(output)
error += u'\nCaptured logging:\n' + output
self.error_message = error
keep_going = False
if not quiet:
for formatter in runner.formatters:
formatter.result(self)
runner.run_hook('after_step', runner.context, self)
return keep_going
class Table(Replayable):
'''A `table`_ extracted from a *feature file*.
Table instance data is accessible using a number of methods:
**iteration**
Iterating over the Table will yield the :class:`~behave.model.Row`
instances from the .rows attribute.
**indexed access**
Individual rows may be accessed directly by index on the Table instance;
table[0] gives the first non-heading row and table[-1] gives the last
row.
The attributes are:
.. attribute:: headings
The headings of the table as a list of strings.
.. attribute:: rows
An list of instances of :class:`~behave.model.Row` that make up the body
of the table in the *feature file*.
Tables are also comparable, for what that's worth. Headings and row data
are compared.
.. _`table`: gherkin.html#table
'''
type = "table"
def __init__(self, headings, line=None, rows=None):
Replayable.__init__(self)
self.headings = headings
self.line = line
self.rows = []
if rows:
for row in rows:
self.add_row(row, line)
def add_row(self, row, line=None):
self.rows.append(Row(self.headings, row, line))
def add_column(self, column_name, values=None, default_value=u""):
"""
Adds a new column to this table.
Uses :param:`default_value` for new cells (if :param:`values` are
not provided). param:`values` are extended with :param:`default_value`
if values list is smaller than the number of table rows.
:param column_name: Name of new column (as string).
:param values: Optional list of cell values in new column.
:param default_value: Default value for cell (if values not provided).
:returns: Index of new column (as number).
"""
# assert isinstance(column_name, unicode)
assert not self.has_column(column_name)
if values is None:
values = [default_value] * len(self.rows)
elif not isinstance(values, list):
values = list(values)
if len(values) < len(self.rows):
more_size = len(self.rows) - len(values)
more_values = [default_value] * more_size
values.extend(more_values)
new_column_index = len(self.headings)
self.headings.append(column_name)
for row, value in zip(self.rows, values):
assert len(row.cells) == new_column_index
row.cells.append(value)
return new_column_index
def remove_column(self, column_name):
if not isinstance(column_name, int):
try:
column_index = self.get_column_index(column_name)
except ValueError:
raise KeyError("column=%s is unknown" % column_name)
assert isinstance(column_index, int)
assert column_index < len(self.headings)
del self.headings[column_index]
for row in self.rows:
assert column_index < len(row.cells)
del row.cells[column_index]
def remove_columns(self, column_names):
for column_name in column_names:
self.remove_column(column_name)
def has_column(self, column_name):
return column_name in self.headings
def get_column_index(self, column_name):
return self.headings.index(column_name)
def require_column(self, column_name):
"""
Require that a column exists in the table.
Raise an AssertionError if the column does not exist.
:param column_name: Name of new column (as string).
:return: Index of column (as number) if it exists.
"""
if not self.has_column(column_name):
columns = ", ".join(self.headings)
msg = "REQUIRE COLUMN: %s (columns: %s)" % (column_name, columns)
raise AssertionError(msg)
return self.get_column_index(column_name)
def require_columns(self, column_names):
for column_name in column_names:
self.require_column(column_name)
def ensure_column_exists(self, column_name):
"""
Ensures that a column with the given name exists.
If the column does not exist, the column is added.
:param column_name: Name of column (as string).
:return: Index of column (as number).
"""
if self.has_column(column_name):
return self.get_column_index(column_name)
else:
return self.add_column(column_name)
def __repr__(self):
return "<Table: %dx%d>" % (len(self.headings), len(self.rows))
def __eq__(self, other):
if isinstance(other, Table):
if self.headings != other.headings:
return False
for my_row, their_row in zip(self.rows, other.rows):
if my_row != their_row:
return False
else:
# -- ASSUME: table <=> raw data comparison
other_rows = other
for my_row, their_row in zip(self.rows, other_rows):
if my_row != their_row:
return False
return True
def __ne__(self, other):
return not self == other
def __iter__(self):
return iter(self.rows)
def __getitem__(self, index):
return self.rows[index]
def assert_equals(self, data):
'''Assert that this table's cells are the same as the supplied "data".
The data passed in must be a list of lists giving:
[
[row 1],
[row 2],
[row 3],
]
If the cells do not match then a useful AssertionError will be raised.
'''
assert self == data
raise NotImplementedError
class Row(object):
'''One row of a `table`_ parsed from a *feature file*.
Row data is accessible using a number of methods:
**iteration**
Iterating over the Row will yield the individual cells as strings.
**named access**
Individual cells may be accessed by heading name; row['name'] would give
the cell value for the column with heading "name".
**indexed access**
Individual cells may be accessed directly by index on the Row instance;
row[0] gives the first cell and row[-1] gives the last cell.
The attributes are:
.. attribute:: cells
The list of strings that form the cells of this row.
.. attribute:: headings
The headings of the table as a list of strings.
Rows are also comparable, for what that's worth. Only the cells are
compared.
.. _`table`: gherkin.html#table
'''
def __init__(self, headings, cells, line=None, comments=None):
self.headings = headings
self.comments = comments
for c in cells:
assert isinstance(c, six.text_type)
self.cells = cells
self.line = line
def __getitem__(self, name):
try:
index = self.headings.index(name)
except ValueError:
if isinstance(name, int):
index = name
else:
raise KeyError('"%s" is not a row heading' % name)
return self.cells[index]
def __repr__(self):
return '<Row %r>' % (self.cells,)
def __eq__(self, other):
return self.cells == other.cells
def __ne__(self, other):
return not self == other
def __len__(self):
return len(self.cells)
def __iter__(self):
return iter(self.cells)
def items(self):
return zip(self.headings, self.cells)
def get(self, key, default=None):
try:
return self[key]
except KeyError:
return default
def as_dict(self):
"""
Converts the row and its cell data into a dictionary.
:return: Row data as dictionary (without comments, line info).
"""
from behave.compat.collections import OrderedDict
return OrderedDict(self.items())
class Tag(six.text_type):
"""Tags appear may be associated with Features or Scenarios.
They're a subclass of regular strings (unicode pre-Python 3) with an
additional ``line`` number attribute (where the tag was seen in the source
feature file.
See :ref:`controlling things with tags`.
"""
def __new__(cls, name, line):
o = six.text_type.__new__(cls, name)
o.line = line
return o
@staticmethod
def make_name(text, unescape=False):
"""Translate text into a "valid tag" without whitespace, etc.
Translation rules are:
* alnum chars => same, kept
* space chars => '_'
* other chars => deleted
:param text: Unicode text as input for name.
:return: Unicode name that can be used as tag.
"""
assert isinstance(text, six.text_type)
if unescape:
# -- UNESCAPE: Some escaped sequences
text = text.replace("\\t", "\t").replace("\\n", "\n")
allowed_chars = u'._-'
chars = []
for char in text:
if char.isalnum() or char in allowed_chars:
chars.append(char)
elif char.isspace():
chars.append(u'_')
return u"".join(chars)
class Text(six.text_type):
'''Store multiline text from a Step definition.
The attributes are:
.. attribute:: value
The actual text parsed from the *feature file*.
.. attribute:: content_type
Currently only 'text/plain'.
'''
def __new__(cls, value, content_type=u'text/plain', line=0):
assert isinstance(value, six.text_type)
assert isinstance(content_type, six.text_type)
o = six.text_type.__new__(cls, value)
o.content_type = content_type
o.line = line
return o
def line_range(self):
line_count = len(self.splitlines())
return (self.line, self.line + line_count + 1)
def replace(self, old, new):
return Text(super(Text, self).replace(old, new), self.content_type,
self.line)
def assert_equals(self, expected):
'''Assert that my text is identical to the "expected" text.
A nice context diff will be displayed if they do not match.
'''
if self == expected:
return True
diff = []
for line in difflib.unified_diff(self.splitlines(),
expected.splitlines()):
diff.append(line)
# strip unnecessary diff prefix
diff = ['Text does not match:'] + diff[3:]
raise AssertionError('\n'.join(diff))
class Match(Replayable):
'''An parameter-matched *feature file* step name extracted using
step decorator `parameters`_.
.. attribute:: func
The step function that this match will be applied to.
.. attribute:: arguments
A list of :class:`behave.model.Argument` instances containing the
matched parameters from the step name.
'''
type = "match"
def __init__(self, func, arguments=None):
super(Match, self).__init__()
self.func = func
self.arguments = arguments
self.location = None
if func:
self.location = self.make_location(func)
def __repr__(self):
if self.func:
func_name = self.func.__name__
else:
func_name = '<no function>'
return '<Match %s, %s>' % (func_name, self.location)
def __eq__(self, other):
if not isinstance(other, Match):
return False
return (self.func, self.location) == (other.func, other.location)
def with_arguments(self, arguments):
match = copy.copy(self)
match.arguments = arguments
return match
def run(self, context):
args = []
kwargs = {}
for arg in self.arguments:
if arg.name is not None:
kwargs[arg.name] = arg.value
else:
args.append(arg.value)
with context.user_mode():
self.func(context, *args, **kwargs)
@staticmethod
def make_location(step_function):
'''
Extracts the location information from the step function and builds
the location string (schema: "{source_filename}:{line_number}").
:param step_function: Function whose location should be determined.
:return: Step function location as string.
'''
step_function_code = six.get_function_code(step_function)
filename = os.path.relpath(step_function_code.co_filename, os.getcwd())
line_number = step_function_code.co_firstlineno
return FileLocation(filename, line_number)
class NoMatch(Match):
'''
Used for an "undefined step" when it can not be matched with a
step definition.
'''
def __init__(self):
Match.__init__(self, func=None)
self.func = None
self.arguments = []
self.location = None
def reset_model(model_elements):
"""
Reset the test run information stored in model elements.
:param model_elements: List of model elements (Feature, Scenario, ...)
"""
for model_element in model_elements:
model_element.reset()
|