Best JavaScript code snippet using fast-check-monorepo
test_argparse.py
Source:test_argparse.py
...1450 parser1 = subparsers.add_parser('1')1451 parser1.add_argument('baz')1452 self.assertEqual(NS(foo=False, bar='1', baz='2'),1453 parser.parse_args('1 2'.split()))1454 def test_help(self):1455 self.assertEqual(self.parser.format_usage(),1456 'usage: PROG [-h] [--foo] bar {1,2} ...\n')1457 self.assertEqual(self.parser.format_help(), textwrap.dedent('''\1458 usage: PROG [-h] [--foo] bar {1,2} ...1459 main description1460 positional arguments:1461 bar bar help1462 {1,2} command help1463 optional arguments:1464 -h, --help show this help message and exit1465 --foo foo help1466 '''))1467 def test_help_extra_prefix_chars(self):1468 # Make sure - is still used for help if it is a non-first prefix char1469 parser = self._get_parser(prefix_chars='+:-')1470 self.assertEqual(parser.format_usage(),1471 'usage: PROG [-h] [++foo] bar {1,2} ...\n')1472 self.assertEqual(parser.format_help(), textwrap.dedent('''\1473 usage: PROG [-h] [++foo] bar {1,2} ...1474 main description1475 positional arguments:1476 bar bar help1477 {1,2} command help1478 optional arguments:1479 -h, --help show this help message and exit1480 ++foo foo help1481 '''))1482 def test_help_alternate_prefix_chars(self):1483 parser = self._get_parser(prefix_chars='+:/')1484 self.assertEqual(parser.format_usage(),1485 'usage: PROG [+h] [++foo] bar {1,2} ...\n')1486 self.assertEqual(parser.format_help(), textwrap.dedent('''\1487 usage: PROG [+h] [++foo] bar {1,2} ...1488 main description1489 positional arguments:1490 bar bar help1491 {1,2} command help1492 optional arguments:1493 +h, ++help show this help message and exit1494 ++foo foo help1495 '''))1496 def test_parser_command_help(self):1497 self.assertEqual(self.command_help_parser.format_usage(),1498 'usage: PROG [-h] [--foo] bar {1,2} ...\n')1499 self.assertEqual(self.command_help_parser.format_help(),1500 textwrap.dedent('''\1501 usage: PROG [-h] [--foo] bar {1,2} ...1502 main description1503 positional arguments:1504 bar bar help1505 {1,2} command help1506 1 1 help1507 2 2 help1508 optional arguments:1509 -h, --help show this help message and exit1510 --foo foo help1511 '''))1512 def test_subparser_title_help(self):1513 parser = ErrorRaisingArgumentParser(prog='PROG',1514 description='main description')1515 parser.add_argument('--foo', action='store_true', help='foo help')1516 parser.add_argument('bar', help='bar help')1517 subparsers = parser.add_subparsers(title='subcommands',1518 description='command help',1519 help='additional text')1520 parser1 = subparsers.add_parser('1')1521 parser2 = subparsers.add_parser('2')1522 self.assertEqual(parser.format_usage(),1523 'usage: PROG [-h] [--foo] bar {1,2} ...\n')1524 self.assertEqual(parser.format_help(), textwrap.dedent('''\1525 usage: PROG [-h] [--foo] bar {1,2} ...1526 main description1527 positional arguments:1528 bar bar help1529 optional arguments:1530 -h, --help show this help message and exit1531 --foo foo help1532 subcommands:1533 command help1534 {1,2} additional text1535 '''))1536 def _test_subparser_help(self, args_str, expected_help):1537 try:1538 self.parser.parse_args(args_str.split())1539 except ArgumentParserError:1540 err = sys.exc_info()[1]1541 if err.stdout != expected_help:1542 print(repr(expected_help))1543 print(repr(err.stdout))1544 self.assertEqual(err.stdout, expected_help)1545 def test_subparser1_help(self):1546 self._test_subparser_help('5.0 1 -h', textwrap.dedent('''\1547 usage: PROG bar 1 [-h] [-w W] {a,b,c}1548 1 description1549 positional arguments:1550 {a,b,c} x help1551 optional arguments:1552 -h, --help show this help message and exit1553 -w W w help1554 '''))1555 def test_subparser2_help(self):1556 self._test_subparser_help('5.0 2 -h', textwrap.dedent('''\1557 usage: PROG bar 2 [-h] [-y {1,2,3}] [z [z ...]]1558 2 description1559 positional arguments:1560 z z help1561 optional arguments:1562 -h, --help show this help message and exit1563 -y {1,2,3} y help1564 '''))1565# ============1566# Groups tests1567# ============1568class TestPositionalsGroups(TestCase):1569 """Tests that order of group positionals matches construction order"""1570 def test_nongroup_first(self):1571 parser = ErrorRaisingArgumentParser()1572 parser.add_argument('foo')1573 group = parser.add_argument_group('g')1574 group.add_argument('bar')1575 parser.add_argument('baz')1576 expected = NS(foo='1', bar='2', baz='3')1577 result = parser.parse_args('1 2 3'.split())1578 self.assertEqual(expected, result)1579 def test_group_first(self):1580 parser = ErrorRaisingArgumentParser()1581 group = parser.add_argument_group('xxx')1582 group.add_argument('foo')1583 parser.add_argument('bar')1584 parser.add_argument('baz')1585 expected = NS(foo='1', bar='2', baz='3')1586 result = parser.parse_args('1 2 3'.split())1587 self.assertEqual(expected, result)1588 def test_interleaved_groups(self):1589 parser = ErrorRaisingArgumentParser()1590 group = parser.add_argument_group('xxx')1591 parser.add_argument('foo')1592 group.add_argument('bar')1593 parser.add_argument('baz')1594 group = parser.add_argument_group('yyy')1595 group.add_argument('frell')1596 expected = NS(foo='1', bar='2', baz='3', frell='4')1597 result = parser.parse_args('1 2 3 4'.split())1598 self.assertEqual(expected, result)1599# ===================1600# Parent parser tests1601# ===================1602class TestParentParsers(TestCase):1603 """Tests that parsers can be created with parent parsers"""1604 def assertArgumentParserError(self, *args, **kwargs):1605 self.assertRaises(ArgumentParserError, *args, **kwargs)1606 def setUp(self):1607 super(TestParentParsers, self).setUp()1608 self.wxyz_parent = ErrorRaisingArgumentParser(add_help=False)1609 self.wxyz_parent.add_argument('--w')1610 x_group = self.wxyz_parent.add_argument_group('x')1611 x_group.add_argument('-y')1612 self.wxyz_parent.add_argument('z')1613 self.abcd_parent = ErrorRaisingArgumentParser(add_help=False)1614 self.abcd_parent.add_argument('a')1615 self.abcd_parent.add_argument('-b')1616 c_group = self.abcd_parent.add_argument_group('c')1617 c_group.add_argument('--d')1618 self.w_parent = ErrorRaisingArgumentParser(add_help=False)1619 self.w_parent.add_argument('--w')1620 self.z_parent = ErrorRaisingArgumentParser(add_help=False)1621 self.z_parent.add_argument('z')1622 # parents with mutually exclusive groups1623 self.ab_mutex_parent = ErrorRaisingArgumentParser(add_help=False)1624 group = self.ab_mutex_parent.add_mutually_exclusive_group()1625 group.add_argument('-a', action='store_true')1626 group.add_argument('-b', action='store_true')1627 self.main_program = os.path.basename(sys.argv[0])1628 def test_single_parent(self):1629 parser = ErrorRaisingArgumentParser(parents=[self.wxyz_parent])1630 self.assertEqual(parser.parse_args('-y 1 2 --w 3'.split()),1631 NS(w='3', y='1', z='2'))1632 def test_single_parent_mutex(self):1633 self._test_mutex_ab(self.ab_mutex_parent.parse_args)1634 parser = ErrorRaisingArgumentParser(parents=[self.ab_mutex_parent])1635 self._test_mutex_ab(parser.parse_args)1636 def test_single_granparent_mutex(self):1637 parents = [self.ab_mutex_parent]1638 parser = ErrorRaisingArgumentParser(add_help=False, parents=parents)1639 parser = ErrorRaisingArgumentParser(parents=[parser])1640 self._test_mutex_ab(parser.parse_args)1641 def _test_mutex_ab(self, parse_args):1642 self.assertEqual(parse_args([]), NS(a=False, b=False))1643 self.assertEqual(parse_args(['-a']), NS(a=True, b=False))1644 self.assertEqual(parse_args(['-b']), NS(a=False, b=True))1645 self.assertArgumentParserError(parse_args, ['-a', '-b'])1646 self.assertArgumentParserError(parse_args, ['-b', '-a'])1647 self.assertArgumentParserError(parse_args, ['-c'])1648 self.assertArgumentParserError(parse_args, ['-a', '-c'])1649 self.assertArgumentParserError(parse_args, ['-b', '-c'])1650 def test_multiple_parents(self):1651 parents = [self.abcd_parent, self.wxyz_parent]1652 parser = ErrorRaisingArgumentParser(parents=parents)1653 self.assertEqual(parser.parse_args('--d 1 --w 2 3 4'.split()),1654 NS(a='3', b=None, d='1', w='2', y=None, z='4'))1655 def test_multiple_parents_mutex(self):1656 parents = [self.ab_mutex_parent, self.wxyz_parent]1657 parser = ErrorRaisingArgumentParser(parents=parents)1658 self.assertEqual(parser.parse_args('-a --w 2 3'.split()),1659 NS(a=True, b=False, w='2', y=None, z='3'))1660 self.assertArgumentParserError(1661 parser.parse_args, '-a --w 2 3 -b'.split())1662 self.assertArgumentParserError(1663 parser.parse_args, '-a -b --w 2 3'.split())1664 def test_conflicting_parents(self):1665 self.assertRaises(1666 argparse.ArgumentError,1667 argparse.ArgumentParser,1668 parents=[self.w_parent, self.wxyz_parent])1669 def test_conflicting_parents_mutex(self):1670 self.assertRaises(1671 argparse.ArgumentError,1672 argparse.ArgumentParser,1673 parents=[self.abcd_parent, self.ab_mutex_parent])1674 def test_same_argument_name_parents(self):1675 parents = [self.wxyz_parent, self.z_parent]1676 parser = ErrorRaisingArgumentParser(parents=parents)1677 self.assertEqual(parser.parse_args('1 2'.split()),1678 NS(w=None, y=None, z='2'))1679 def test_subparser_parents(self):1680 parser = ErrorRaisingArgumentParser()1681 subparsers = parser.add_subparsers()1682 abcde_parser = subparsers.add_parser('bar', parents=[self.abcd_parent])1683 abcde_parser.add_argument('e')1684 self.assertEqual(parser.parse_args('bar -b 1 --d 2 3 4'.split()),1685 NS(a='3', b='1', d='2', e='4'))1686 def test_subparser_parents_mutex(self):1687 parser = ErrorRaisingArgumentParser()1688 subparsers = parser.add_subparsers()1689 parents = [self.ab_mutex_parent]1690 abc_parser = subparsers.add_parser('foo', parents=parents)1691 c_group = abc_parser.add_argument_group('c_group')1692 c_group.add_argument('c')1693 parents = [self.wxyz_parent, self.ab_mutex_parent]1694 wxyzabe_parser = subparsers.add_parser('bar', parents=parents)1695 wxyzabe_parser.add_argument('e')1696 self.assertEqual(parser.parse_args('foo -a 4'.split()),1697 NS(a=True, b=False, c='4'))1698 self.assertEqual(parser.parse_args('bar -b --w 2 3 4'.split()),1699 NS(a=False, b=True, w='2', y=None, z='3', e='4'))1700 self.assertArgumentParserError(1701 parser.parse_args, 'foo -a -b 4'.split())1702 self.assertArgumentParserError(1703 parser.parse_args, 'bar -b -a 4'.split())1704 def test_parent_help(self):1705 parents = [self.abcd_parent, self.wxyz_parent]1706 parser = ErrorRaisingArgumentParser(parents=parents)1707 parser_help = parser.format_help()1708 progname = self.main_program1709 self.assertEqual(parser_help, textwrap.dedent('''\1710 usage: {}{}[-h] [-b B] [--d D] [--w W] [-y Y] a z1711 positional arguments:1712 a1713 z1714 optional arguments:1715 -h, --help show this help message and exit1716 -b B1717 --w W1718 c:1719 --d D1720 x:1721 -y Y1722 '''.format(progname, ' ' if progname else '' )))1723 def test_groups_parents(self):1724 parent = ErrorRaisingArgumentParser(add_help=False)1725 g = parent.add_argument_group(title='g', description='gd')1726 g.add_argument('-w')1727 g.add_argument('-x')1728 m = parent.add_mutually_exclusive_group()1729 m.add_argument('-y')1730 m.add_argument('-z')1731 parser = ErrorRaisingArgumentParser(parents=[parent])1732 self.assertRaises(ArgumentParserError, parser.parse_args,1733 ['-y', 'Y', '-z', 'Z'])1734 parser_help = parser.format_help()1735 progname = self.main_program1736 self.assertEqual(parser_help, textwrap.dedent('''\1737 usage: {}{}[-h] [-w W] [-x X] [-y Y | -z Z]1738 optional arguments:1739 -h, --help show this help message and exit1740 -y Y1741 -z Z1742 g:1743 gd1744 -w W1745 -x X1746 '''.format(progname, ' ' if progname else '' )))1747# ==============================1748# Mutually exclusive group tests1749# ==============================1750class TestMutuallyExclusiveGroupErrors(TestCase):1751 def test_invalid_add_argument_group(self):1752 parser = ErrorRaisingArgumentParser()1753 raises = self.assertRaises1754 raises(TypeError, parser.add_mutually_exclusive_group, title='foo')1755 def test_invalid_add_argument(self):1756 parser = ErrorRaisingArgumentParser()1757 group = parser.add_mutually_exclusive_group()1758 add_argument = group.add_argument1759 raises = self.assertRaises1760 raises(ValueError, add_argument, '--foo', required=True)1761 raises(ValueError, add_argument, 'bar')1762 raises(ValueError, add_argument, 'bar', nargs='+')1763 raises(ValueError, add_argument, 'bar', nargs=1)1764 raises(ValueError, add_argument, 'bar', nargs=argparse.PARSER)1765 def test_help(self):1766 parser = ErrorRaisingArgumentParser(prog='PROG')1767 group1 = parser.add_mutually_exclusive_group()1768 group1.add_argument('--foo', action='store_true')1769 group1.add_argument('--bar', action='store_false')1770 group2 = parser.add_mutually_exclusive_group()1771 group2.add_argument('--soup', action='store_true')1772 group2.add_argument('--nuts', action='store_false')1773 expected = '''\1774 usage: PROG [-h] [--foo | --bar] [--soup | --nuts]1775 optional arguments:1776 -h, --help show this help message and exit1777 --foo1778 --bar1779 --soup1780 --nuts1781 '''1782 self.assertEqual(parser.format_help(), textwrap.dedent(expected))1783class MEMixin(object):1784 def test_failures_when_not_required(self):1785 parse_args = self.get_parser(required=False).parse_args1786 error = ArgumentParserError1787 for args_string in self.failures:1788 self.assertRaises(error, parse_args, args_string.split())1789 def test_failures_when_required(self):1790 parse_args = self.get_parser(required=True).parse_args1791 error = ArgumentParserError1792 for args_string in self.failures + ['']:1793 self.assertRaises(error, parse_args, args_string.split())1794 def test_successes_when_not_required(self):1795 parse_args = self.get_parser(required=False).parse_args1796 successes = self.successes + self.successes_when_not_required1797 for args_string, expected_ns in successes:1798 actual_ns = parse_args(args_string.split())1799 self.assertEqual(actual_ns, expected_ns)1800 def test_successes_when_required(self):1801 parse_args = self.get_parser(required=True).parse_args1802 for args_string, expected_ns in self.successes:1803 actual_ns = parse_args(args_string.split())1804 self.assertEqual(actual_ns, expected_ns)1805 def test_usage_when_not_required(self):1806 format_usage = self.get_parser(required=False).format_usage1807 expected_usage = self.usage_when_not_required1808 self.assertEqual(format_usage(), textwrap.dedent(expected_usage))1809 def test_usage_when_required(self):1810 format_usage = self.get_parser(required=True).format_usage1811 expected_usage = self.usage_when_required1812 self.assertEqual(format_usage(), textwrap.dedent(expected_usage))1813 def test_help_when_not_required(self):1814 format_help = self.get_parser(required=False).format_help1815 help = self.usage_when_not_required + self.help1816 self.assertEqual(format_help(), textwrap.dedent(help))1817 def test_help_when_required(self):1818 format_help = self.get_parser(required=True).format_help1819 help = self.usage_when_required + self.help1820 self.assertEqual(format_help(), textwrap.dedent(help))1821class TestMutuallyExclusiveSimple(MEMixin, TestCase):1822 def get_parser(self, required=None):1823 parser = ErrorRaisingArgumentParser(prog='PROG')1824 group = parser.add_mutually_exclusive_group(required=required)1825 group.add_argument('--bar', help='bar help')1826 group.add_argument('--baz', nargs='?', const='Z', help='baz help')1827 return parser1828 failures = ['--bar X --baz Y', '--bar X --baz']1829 successes = [1830 ('--bar X', NS(bar='X', baz=None)),1831 ('--bar X --bar Z', NS(bar='Z', baz=None)),1832 ('--baz Y', NS(bar=None, baz='Y')),1833 ('--baz', NS(bar=None, baz='Z')),1834 ]1835 successes_when_not_required = [1836 ('', NS(bar=None, baz=None)),1837 ]1838 usage_when_not_required = '''\1839 usage: PROG [-h] [--bar BAR | --baz [BAZ]]1840 '''1841 usage_when_required = '''\1842 usage: PROG [-h] (--bar BAR | --baz [BAZ])1843 '''1844 help = '''\1845 optional arguments:1846 -h, --help show this help message and exit1847 --bar BAR bar help1848 --baz [BAZ] baz help1849 '''1850class TestMutuallyExclusiveLong(MEMixin, TestCase):1851 def get_parser(self, required=None):1852 parser = ErrorRaisingArgumentParser(prog='PROG')1853 parser.add_argument('--abcde', help='abcde help')1854 parser.add_argument('--fghij', help='fghij help')1855 group = parser.add_mutually_exclusive_group(required=required)1856 group.add_argument('--klmno', help='klmno help')1857 group.add_argument('--pqrst', help='pqrst help')1858 return parser1859 failures = ['--klmno X --pqrst Y']1860 successes = [1861 ('--klmno X', NS(abcde=None, fghij=None, klmno='X', pqrst=None)),1862 ('--abcde Y --klmno X',1863 NS(abcde='Y', fghij=None, klmno='X', pqrst=None)),1864 ('--pqrst X', NS(abcde=None, fghij=None, klmno=None, pqrst='X')),1865 ('--pqrst X --fghij Y',1866 NS(abcde=None, fghij='Y', klmno=None, pqrst='X')),1867 ]1868 successes_when_not_required = [1869 ('', NS(abcde=None, fghij=None, klmno=None, pqrst=None)),1870 ]1871 usage_when_not_required = '''\1872 usage: PROG [-h] [--abcde ABCDE] [--fghij FGHIJ]1873 [--klmno KLMNO | --pqrst PQRST]1874 '''1875 usage_when_required = '''\1876 usage: PROG [-h] [--abcde ABCDE] [--fghij FGHIJ]1877 (--klmno KLMNO | --pqrst PQRST)1878 '''1879 help = '''\1880 optional arguments:1881 -h, --help show this help message and exit1882 --abcde ABCDE abcde help1883 --fghij FGHIJ fghij help1884 --klmno KLMNO klmno help1885 --pqrst PQRST pqrst help1886 '''1887class TestMutuallyExclusiveFirstSuppressed(MEMixin, TestCase):1888 def get_parser(self, required):1889 parser = ErrorRaisingArgumentParser(prog='PROG')1890 group = parser.add_mutually_exclusive_group(required=required)1891 group.add_argument('-x', help=argparse.SUPPRESS)1892 group.add_argument('-y', action='store_false', help='y help')1893 return parser1894 failures = ['-x X -y']1895 successes = [1896 ('-x X', NS(x='X', y=True)),1897 ('-x X -x Y', NS(x='Y', y=True)),1898 ('-y', NS(x=None, y=False)),1899 ]1900 successes_when_not_required = [1901 ('', NS(x=None, y=True)),1902 ]1903 usage_when_not_required = '''\1904 usage: PROG [-h] [-y]1905 '''1906 usage_when_required = '''\1907 usage: PROG [-h] -y1908 '''1909 help = '''\1910 optional arguments:1911 -h, --help show this help message and exit1912 -y y help1913 '''1914class TestMutuallyExclusiveManySuppressed(MEMixin, TestCase):1915 def get_parser(self, required):1916 parser = ErrorRaisingArgumentParser(prog='PROG')1917 group = parser.add_mutually_exclusive_group(required=required)1918 add = group.add_argument1919 add('--spam', action='store_true', help=argparse.SUPPRESS)1920 add('--badger', action='store_false', help=argparse.SUPPRESS)1921 add('--bladder', help=argparse.SUPPRESS)1922 return parser1923 failures = [1924 '--spam --badger',1925 '--badger --bladder B',1926 '--bladder B --spam',1927 ]1928 successes = [1929 ('--spam', NS(spam=True, badger=True, bladder=None)),1930 ('--badger', NS(spam=False, badger=False, bladder=None)),1931 ('--bladder B', NS(spam=False, badger=True, bladder='B')),1932 ('--spam --spam', NS(spam=True, badger=True, bladder=None)),1933 ]1934 successes_when_not_required = [1935 ('', NS(spam=False, badger=True, bladder=None)),1936 ]1937 usage_when_required = usage_when_not_required = '''\1938 usage: PROG [-h]1939 '''1940 help = '''\1941 optional arguments:1942 -h, --help show this help message and exit1943 '''1944class TestMutuallyExclusiveOptionalAndPositional(MEMixin, TestCase):1945 def get_parser(self, required):1946 parser = ErrorRaisingArgumentParser(prog='PROG')1947 group = parser.add_mutually_exclusive_group(required=required)1948 group.add_argument('--foo', action='store_true', help='FOO')1949 group.add_argument('--spam', help='SPAM')1950 group.add_argument('badger', nargs='*', default='X', help='BADGER')1951 return parser1952 failures = [1953 '--foo --spam S',1954 '--spam S X',1955 'X --foo',1956 'X Y Z --spam S',1957 '--foo X Y',1958 ]1959 successes = [1960 ('--foo', NS(foo=True, spam=None, badger='X')),1961 ('--spam S', NS(foo=False, spam='S', badger='X')),1962 ('X', NS(foo=False, spam=None, badger=['X'])),1963 ('X Y Z', NS(foo=False, spam=None, badger=['X', 'Y', 'Z'])),1964 ]1965 successes_when_not_required = [1966 ('', NS(foo=False, spam=None, badger='X')),1967 ]1968 usage_when_not_required = '''\1969 usage: PROG [-h] [--foo | --spam SPAM | badger [badger ...]]1970 '''1971 usage_when_required = '''\1972 usage: PROG [-h] (--foo | --spam SPAM | badger [badger ...])1973 '''1974 help = '''\1975 positional arguments:1976 badger BADGER1977 optional arguments:1978 -h, --help show this help message and exit1979 --foo FOO1980 --spam SPAM SPAM1981 '''1982class TestMutuallyExclusiveOptionalsMixed(MEMixin, TestCase):1983 def get_parser(self, required):1984 parser = ErrorRaisingArgumentParser(prog='PROG')1985 parser.add_argument('-x', action='store_true', help='x help')1986 group = parser.add_mutually_exclusive_group(required=required)1987 group.add_argument('-a', action='store_true', help='a help')1988 group.add_argument('-b', action='store_true', help='b help')1989 parser.add_argument('-y', action='store_true', help='y help')1990 group.add_argument('-c', action='store_true', help='c help')1991 return parser1992 failures = ['-a -b', '-b -c', '-a -c', '-a -b -c']1993 successes = [1994 ('-a', NS(a=True, b=False, c=False, x=False, y=False)),1995 ('-b', NS(a=False, b=True, c=False, x=False, y=False)),1996 ('-c', NS(a=False, b=False, c=True, x=False, y=False)),1997 ('-a -x', NS(a=True, b=False, c=False, x=True, y=False)),1998 ('-y -b', NS(a=False, b=True, c=False, x=False, y=True)),1999 ('-x -y -c', NS(a=False, b=False, c=True, x=True, y=True)),2000 ]2001 successes_when_not_required = [2002 ('', NS(a=False, b=False, c=False, x=False, y=False)),2003 ('-x', NS(a=False, b=False, c=False, x=True, y=False)),2004 ('-y', NS(a=False, b=False, c=False, x=False, y=True)),2005 ]2006 usage_when_required = usage_when_not_required = '''\2007 usage: PROG [-h] [-x] [-a] [-b] [-y] [-c]2008 '''2009 help = '''\2010 optional arguments:2011 -h, --help show this help message and exit2012 -x x help2013 -a a help2014 -b b help2015 -y y help2016 -c c help2017 '''2018class TestMutuallyExclusiveInGroup(MEMixin, TestCase):2019 def get_parser(self, required=None):2020 parser = ErrorRaisingArgumentParser(prog='PROG')2021 titled_group = parser.add_argument_group(2022 title='Titled group', description='Group description')2023 mutex_group = \2024 titled_group.add_mutually_exclusive_group(required=required)2025 mutex_group.add_argument('--bar', help='bar help')2026 mutex_group.add_argument('--baz', help='baz help')2027 return parser2028 failures = ['--bar X --baz Y', '--baz X --bar Y']2029 successes = [2030 ('--bar X', NS(bar='X', baz=None)),2031 ('--baz Y', NS(bar=None, baz='Y')),2032 ]2033 successes_when_not_required = [2034 ('', NS(bar=None, baz=None)),2035 ]2036 usage_when_not_required = '''\2037 usage: PROG [-h] [--bar BAR | --baz BAZ]2038 '''2039 usage_when_required = '''\2040 usage: PROG [-h] (--bar BAR | --baz BAZ)2041 '''2042 help = '''\2043 optional arguments:2044 -h, --help show this help message and exit2045 Titled group:2046 Group description2047 --bar BAR bar help2048 --baz BAZ baz help2049 '''2050class TestMutuallyExclusiveOptionalsAndPositionalsMixed(MEMixin, TestCase):2051 def get_parser(self, required):2052 parser = ErrorRaisingArgumentParser(prog='PROG')2053 parser.add_argument('x', help='x help')2054 parser.add_argument('-y', action='store_true', help='y help')2055 group = parser.add_mutually_exclusive_group(required=required)2056 group.add_argument('a', nargs='?', help='a help')2057 group.add_argument('-b', action='store_true', help='b help')2058 group.add_argument('-c', action='store_true', help='c help')2059 return parser2060 failures = ['X A -b', '-b -c', '-c X A']2061 successes = [2062 ('X A', NS(a='A', b=False, c=False, x='X', y=False)),2063 ('X -b', NS(a=None, b=True, c=False, x='X', y=False)),2064 ('X -c', NS(a=None, b=False, c=True, x='X', y=False)),2065 ('X A -y', NS(a='A', b=False, c=False, x='X', y=True)),2066 ('X -y -b', NS(a=None, b=True, c=False, x='X', y=True)),2067 ]2068 successes_when_not_required = [2069 ('X', NS(a=None, b=False, c=False, x='X', y=False)),2070 ('X -y', NS(a=None, b=False, c=False, x='X', y=True)),2071 ]2072 usage_when_required = usage_when_not_required = '''\2073 usage: PROG [-h] [-y] [-b] [-c] x [a]2074 '''2075 help = '''\2076 positional arguments:2077 x x help2078 a a help2079 optional arguments:2080 -h, --help show this help message and exit2081 -y y help2082 -b b help2083 -c c help2084 '''2085# =================================================2086# Mutually exclusive group in parent parser tests2087# =================================================2088class MEPBase(object):2089 def get_parser(self, required=None):2090 parent = super(MEPBase, self).get_parser(required=required)2091 parser = ErrorRaisingArgumentParser(2092 prog=parent.prog, add_help=False, parents=[parent])2093 return parser2094class TestMutuallyExclusiveGroupErrorsParent(2095 MEPBase, TestMutuallyExclusiveGroupErrors):2096 pass2097class TestMutuallyExclusiveSimpleParent(2098 MEPBase, TestMutuallyExclusiveSimple):2099 pass2100class TestMutuallyExclusiveLongParent(2101 MEPBase, TestMutuallyExclusiveLong):2102 pass2103class TestMutuallyExclusiveFirstSuppressedParent(2104 MEPBase, TestMutuallyExclusiveFirstSuppressed):2105 pass2106class TestMutuallyExclusiveManySuppressedParent(2107 MEPBase, TestMutuallyExclusiveManySuppressed):2108 pass2109class TestMutuallyExclusiveOptionalAndPositionalParent(2110 MEPBase, TestMutuallyExclusiveOptionalAndPositional):2111 pass2112class TestMutuallyExclusiveOptionalsMixedParent(2113 MEPBase, TestMutuallyExclusiveOptionalsMixed):2114 pass2115class TestMutuallyExclusiveOptionalsAndPositionalsMixedParent(2116 MEPBase, TestMutuallyExclusiveOptionalsAndPositionalsMixed):2117 pass2118# =================2119# Set default tests2120# =================2121class TestSetDefaults(TestCase):2122 def test_set_defaults_no_args(self):2123 parser = ErrorRaisingArgumentParser()2124 parser.set_defaults(x='foo')2125 parser.set_defaults(y='bar', z=1)2126 self.assertEqual(NS(x='foo', y='bar', z=1),2127 parser.parse_args([]))2128 self.assertEqual(NS(x='foo', y='bar', z=1),2129 parser.parse_args([], NS()))2130 self.assertEqual(NS(x='baz', y='bar', z=1),2131 parser.parse_args([], NS(x='baz')))2132 self.assertEqual(NS(x='baz', y='bar', z=2),2133 parser.parse_args([], NS(x='baz', z=2)))2134 def test_set_defaults_with_args(self):2135 parser = ErrorRaisingArgumentParser()2136 parser.set_defaults(x='foo', y='bar')2137 parser.add_argument('-x', default='xfoox')2138 self.assertEqual(NS(x='xfoox', y='bar'),2139 parser.parse_args([]))2140 self.assertEqual(NS(x='xfoox', y='bar'),2141 parser.parse_args([], NS()))2142 self.assertEqual(NS(x='baz', y='bar'),2143 parser.parse_args([], NS(x='baz')))2144 self.assertEqual(NS(x='1', y='bar'),2145 parser.parse_args('-x 1'.split()))2146 self.assertEqual(NS(x='1', y='bar'),2147 parser.parse_args('-x 1'.split(), NS()))2148 self.assertEqual(NS(x='1', y='bar'),2149 parser.parse_args('-x 1'.split(), NS(x='baz')))2150 def test_set_defaults_subparsers(self):2151 parser = ErrorRaisingArgumentParser()2152 parser.set_defaults(x='foo')2153 subparsers = parser.add_subparsers()2154 parser_a = subparsers.add_parser('a')2155 parser_a.set_defaults(y='bar')2156 self.assertEqual(NS(x='foo', y='bar'),2157 parser.parse_args('a'.split()))2158 def test_set_defaults_parents(self):2159 parent = ErrorRaisingArgumentParser(add_help=False)2160 parent.set_defaults(x='foo')2161 parser = ErrorRaisingArgumentParser(parents=[parent])2162 self.assertEqual(NS(x='foo'), parser.parse_args([]))2163 def test_set_defaults_same_as_add_argument(self):2164 parser = ErrorRaisingArgumentParser()2165 parser.set_defaults(w='W', x='X', y='Y', z='Z')2166 parser.add_argument('-w')2167 parser.add_argument('-x', default='XX')2168 parser.add_argument('y', nargs='?')2169 parser.add_argument('z', nargs='?', default='ZZ')2170 # defaults set previously2171 self.assertEqual(NS(w='W', x='XX', y='Y', z='ZZ'),2172 parser.parse_args([]))2173 # reset defaults2174 parser.set_defaults(w='WW', x='X', y='YY', z='Z')2175 self.assertEqual(NS(w='WW', x='X', y='YY', z='Z'),2176 parser.parse_args([]))2177 def test_set_defaults_same_as_add_argument_group(self):2178 parser = ErrorRaisingArgumentParser()2179 parser.set_defaults(w='W', x='X', y='Y', z='Z')2180 group = parser.add_argument_group('foo')2181 group.add_argument('-w')2182 group.add_argument('-x', default='XX')2183 group.add_argument('y', nargs='?')2184 group.add_argument('z', nargs='?', default='ZZ')2185 # defaults set previously2186 self.assertEqual(NS(w='W', x='XX', y='Y', z='ZZ'),2187 parser.parse_args([]))2188 # reset defaults2189 parser.set_defaults(w='WW', x='X', y='YY', z='Z')2190 self.assertEqual(NS(w='WW', x='X', y='YY', z='Z'),2191 parser.parse_args([]))2192# =================2193# Get default tests2194# =================2195class TestGetDefault(TestCase):2196 def test_get_default(self):2197 parser = ErrorRaisingArgumentParser()2198 self.assertEqual(None, parser.get_default("foo"))2199 self.assertEqual(None, parser.get_default("bar"))2200 parser.add_argument("--foo")2201 self.assertEqual(None, parser.get_default("foo"))2202 self.assertEqual(None, parser.get_default("bar"))2203 parser.add_argument("--bar", type=int, default=42)2204 self.assertEqual(None, parser.get_default("foo"))2205 self.assertEqual(42, parser.get_default("bar"))2206 parser.set_defaults(foo="badger")2207 self.assertEqual("badger", parser.get_default("foo"))2208 self.assertEqual(42, parser.get_default("bar"))2209# ==========================2210# Namespace 'contains' tests2211# ==========================2212class TestNamespaceContainsSimple(TestCase):2213 def test_empty(self):2214 ns = argparse.Namespace()2215 self.assertEqual('' in ns, False)2216 self.assertEqual('' not in ns, True)2217 self.assertEqual('x' in ns, False)2218 def test_non_empty(self):2219 ns = argparse.Namespace(x=1, y=2)2220 self.assertEqual('x' in ns, True)2221 self.assertEqual('x' not in ns, False)2222 self.assertEqual('y' in ns, True)2223 self.assertEqual('' in ns, False)2224 self.assertEqual('xx' in ns, False)2225 self.assertEqual('z' in ns, False)2226# =====================2227# Help formatting tests2228# =====================2229class TestHelpFormattingMetaclass(type):2230 def __init__(cls, name, bases, bodydict):2231 if name == 'HelpTestCase':2232 return2233 class AddTests(object):2234 def __init__(self, test_class, func_suffix, std_name):2235 self.func_suffix = func_suffix2236 self.std_name = std_name2237 for test_func in [self.test_format,2238 self.test_print,2239 self.test_print_file]:2240 test_name = '%s_%s' % (test_func.__name__, func_suffix)2241 def test_wrapper(self, test_func=test_func):2242 test_func(self)2243 try:2244 test_wrapper.__name__ = test_name2245 except TypeError:2246 pass2247 setattr(test_class, test_name, test_wrapper)2248 def _get_parser(self, tester):2249 parser = argparse.ArgumentParser(2250 *tester.parser_signature.args,2251 **tester.parser_signature.kwargs)2252 for argument_sig in getattr(tester, 'argument_signatures', []):2253 parser.add_argument(*argument_sig.args,2254 **argument_sig.kwargs)2255 group_sigs = getattr(tester, 'argument_group_signatures', [])2256 for group_sig, argument_sigs in group_sigs:2257 group = parser.add_argument_group(*group_sig.args,2258 **group_sig.kwargs)2259 for argument_sig in argument_sigs:2260 group.add_argument(*argument_sig.args,2261 **argument_sig.kwargs)2262 subparsers_sigs = getattr(tester, 'subparsers_signatures', [])2263 if subparsers_sigs:2264 subparsers = parser.add_subparsers()2265 for subparser_sig in subparsers_sigs:2266 subparsers.add_parser(*subparser_sig.args,2267 **subparser_sig.kwargs)2268 return parser2269 def _test(self, tester, parser_text):2270 expected_text = getattr(tester, self.func_suffix)2271 expected_text = textwrap.dedent(expected_text)2272 if expected_text != parser_text:2273 print(repr(expected_text))2274 print(repr(parser_text))2275 for char1, char2 in zip(expected_text, parser_text):2276 if char1 != char2:2277 print('first diff: %r %r' % (char1, char2))2278 break2279 tester.assertEqual(expected_text, parser_text)2280 def test_format(self, tester):2281 parser = self._get_parser(tester)2282 format = getattr(parser, 'format_%s' % self.func_suffix)2283 self._test(tester, format())2284 def test_print(self, tester):2285 parser = self._get_parser(tester)2286 print_ = getattr(parser, 'print_%s' % self.func_suffix)2287 old_stream = getattr(sys, self.std_name)2288 setattr(sys, self.std_name, StdIOBuffer())2289 try:2290 print_()2291 parser_text = getattr(sys, self.std_name).getvalue()2292 finally:2293 setattr(sys, self.std_name, old_stream)2294 self._test(tester, parser_text)2295 def test_print_file(self, tester):2296 parser = self._get_parser(tester)2297 print_ = getattr(parser, 'print_%s' % self.func_suffix)2298 sfile = StdIOBuffer()2299 print_(sfile)2300 parser_text = sfile.getvalue()2301 self._test(tester, parser_text)2302 # add tests for {format,print}_{usage,help,version}2303 for func_suffix, std_name in [('usage', 'stdout'),2304 ('help', 'stdout'),2305 ('version', 'stderr')]:2306 AddTests(cls, func_suffix, std_name)2307bases = TestCase,2308HelpTestCase = TestHelpFormattingMetaclass('HelpTestCase', bases, {})2309class TestHelpBiggerOptionals(HelpTestCase):2310 """Make sure that argument help aligns when options are longer"""2311 parser_signature = Sig(prog='PROG', description='DESCRIPTION',2312 epilog='EPILOG', version='0.1')2313 argument_signatures = [2314 Sig('-x', action='store_true', help='X HELP'),2315 Sig('--y', help='Y HELP'),2316 Sig('foo', help='FOO HELP'),2317 Sig('bar', help='BAR HELP'),2318 ]2319 argument_group_signatures = []2320 usage = '''\2321 usage: PROG [-h] [-v] [-x] [--y Y] foo bar2322 '''2323 help = usage + '''\2324 DESCRIPTION2325 positional arguments:2326 foo FOO HELP2327 bar BAR HELP2328 optional arguments:2329 -h, --help show this help message and exit2330 -v, --version show program's version number and exit2331 -x X HELP2332 --y Y Y HELP2333 EPILOG2334 '''2335 version = '''\2336 0.12337 '''2338class TestHelpBiggerOptionalGroups(HelpTestCase):2339 """Make sure that argument help aligns when options are longer"""2340 parser_signature = Sig(prog='PROG', description='DESCRIPTION',2341 epilog='EPILOG', version='0.1')2342 argument_signatures = [2343 Sig('-x', action='store_true', help='X HELP'),2344 Sig('--y', help='Y HELP'),2345 Sig('foo', help='FOO HELP'),2346 Sig('bar', help='BAR HELP'),2347 ]2348 argument_group_signatures = [2349 (Sig('GROUP TITLE', description='GROUP DESCRIPTION'), [2350 Sig('baz', help='BAZ HELP'),2351 Sig('-z', nargs='+', help='Z HELP')]),2352 ]2353 usage = '''\2354 usage: PROG [-h] [-v] [-x] [--y Y] [-z Z [Z ...]] foo bar baz2355 '''2356 help = usage + '''\2357 DESCRIPTION2358 positional arguments:2359 foo FOO HELP2360 bar BAR HELP2361 optional arguments:2362 -h, --help show this help message and exit2363 -v, --version show program's version number and exit2364 -x X HELP2365 --y Y Y HELP2366 GROUP TITLE:2367 GROUP DESCRIPTION2368 baz BAZ HELP2369 -z Z [Z ...] Z HELP2370 EPILOG2371 '''2372 version = '''\2373 0.12374 '''2375class TestHelpBiggerPositionals(HelpTestCase):2376 """Make sure that help aligns when arguments are longer"""2377 parser_signature = Sig(usage='USAGE', description='DESCRIPTION')2378 argument_signatures = [2379 Sig('-x', action='store_true', help='X HELP'),2380 Sig('--y', help='Y HELP'),2381 Sig('ekiekiekifekang', help='EKI HELP'),2382 Sig('bar', help='BAR HELP'),2383 ]2384 argument_group_signatures = []2385 usage = '''\2386 usage: USAGE2387 '''2388 help = usage + '''\2389 DESCRIPTION2390 positional arguments:2391 ekiekiekifekang EKI HELP2392 bar BAR HELP2393 optional arguments:2394 -h, --help show this help message and exit2395 -x X HELP2396 --y Y Y HELP2397 '''2398 version = ''2399class TestHelpReformatting(HelpTestCase):2400 """Make sure that text after short names starts on the first line"""2401 parser_signature = Sig(2402 prog='PROG',2403 description=' oddly formatted\n'2404 'description\n'2405 '\n'2406 'that is so long that it should go onto multiple '2407 'lines when wrapped')2408 argument_signatures = [2409 Sig('-x', metavar='XX', help='oddly\n'2410 ' formatted -x help'),2411 Sig('y', metavar='yyy', help='normal y help'),2412 ]2413 argument_group_signatures = [2414 (Sig('title', description='\n'2415 ' oddly formatted group\n'2416 '\n'2417 'description'),2418 [Sig('-a', action='store_true',2419 help=' oddly \n'2420 'formatted -a help \n'2421 ' again, so long that it should be wrapped over '2422 'multiple lines')]),2423 ]2424 usage = '''\2425 usage: PROG [-h] [-x XX] [-a] yyy2426 '''2427 help = usage + '''\2428 oddly formatted description that is so long that it should go onto \2429multiple2430 lines when wrapped2431 positional arguments:2432 yyy normal y help2433 optional arguments:2434 -h, --help show this help message and exit2435 -x XX oddly formatted -x help2436 title:2437 oddly formatted group description2438 -a oddly formatted -a help again, so long that it should \2439be wrapped2440 over multiple lines2441 '''2442 version = ''2443class TestHelpWrappingShortNames(HelpTestCase):2444 """Make sure that text after short names starts on the first line"""2445 parser_signature = Sig(prog='PROG', description= 'D\nD' * 30)2446 argument_signatures = [2447 Sig('-x', metavar='XX', help='XHH HX' * 20),2448 Sig('y', metavar='yyy', help='YH YH' * 20),2449 ]2450 argument_group_signatures = [2451 (Sig('ALPHAS'), [2452 Sig('-a', action='store_true', help='AHHH HHA' * 10)]),2453 ]2454 usage = '''\2455 usage: PROG [-h] [-x XX] [-a] yyy2456 '''2457 help = usage + '''\2458 D DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD \2459DD DD DD2460 DD DD DD DD D2461 positional arguments:2462 yyy YH YHYH YHYH YHYH YHYH YHYH YHYH YHYH YHYH YHYH YHYH \2463YHYH YHYH2464 YHYH YHYH YHYH YHYH YHYH YHYH YHYH YH2465 optional arguments:2466 -h, --help show this help message and exit2467 -x XX XHH HXXHH HXXHH HXXHH HXXHH HXXHH HXXHH HXXHH HXXHH \2468HXXHH HXXHH2469 HXXHH HXXHH HXXHH HXXHH HXXHH HXXHH HXXHH HXXHH HXXHH HX2470 ALPHAS:2471 -a AHHH HHAAHHH HHAAHHH HHAAHHH HHAAHHH HHAAHHH HHAAHHH \2472HHAAHHH2473 HHAAHHH HHAAHHH HHA2474 '''2475 version = ''2476class TestHelpWrappingLongNames(HelpTestCase):2477 """Make sure that text after long names starts on the next line"""2478 parser_signature = Sig(usage='USAGE', description= 'D D' * 30,2479 version='V V'*30)2480 argument_signatures = [2481 Sig('-x', metavar='X' * 25, help='XH XH' * 20),2482 Sig('y', metavar='y' * 25, help='YH YH' * 20),2483 ]2484 argument_group_signatures = [2485 (Sig('ALPHAS'), [2486 Sig('-a', metavar='A' * 25, help='AH AH' * 20),2487 Sig('z', metavar='z' * 25, help='ZH ZH' * 20)]),2488 ]2489 usage = '''\2490 usage: USAGE2491 '''2492 help = usage + '''\2493 D DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD \2494DD DD DD2495 DD DD DD DD D2496 positional arguments:2497 yyyyyyyyyyyyyyyyyyyyyyyyy2498 YH YHYH YHYH YHYH YHYH YHYH YHYH YHYH YHYH \2499YHYH YHYH2500 YHYH YHYH YHYH YHYH YHYH YHYH YHYH YHYH YHYH YH2501 optional arguments:2502 -h, --help show this help message and exit2503 -v, --version show program's version number and exit2504 -x XXXXXXXXXXXXXXXXXXXXXXXXX2505 XH XHXH XHXH XHXH XHXH XHXH XHXH XHXH XHXH \2506XHXH XHXH2507 XHXH XHXH XHXH XHXH XHXH XHXH XHXH XHXH XHXH XH2508 ALPHAS:2509 -a AAAAAAAAAAAAAAAAAAAAAAAAA2510 AH AHAH AHAH AHAH AHAH AHAH AHAH AHAH AHAH \2511AHAH AHAH2512 AHAH AHAH AHAH AHAH AHAH AHAH AHAH AHAH AHAH AH2513 zzzzzzzzzzzzzzzzzzzzzzzzz2514 ZH ZHZH ZHZH ZHZH ZHZH ZHZH ZHZH ZHZH ZHZH \2515ZHZH ZHZH2516 ZHZH ZHZH ZHZH ZHZH ZHZH ZHZH ZHZH ZHZH ZHZH ZH2517 '''2518 version = '''\2519 V VV VV VV VV VV VV VV VV VV VV VV VV VV VV VV VV VV VV VV VV VV VV \2520VV VV VV2521 VV VV VV VV V2522 '''2523class TestHelpUsage(HelpTestCase):2524 """Test basic usage messages"""2525 parser_signature = Sig(prog='PROG')2526 argument_signatures = [2527 Sig('-w', nargs='+', help='w'),2528 Sig('-x', nargs='*', help='x'),2529 Sig('a', help='a'),2530 Sig('b', help='b', nargs=2),2531 Sig('c', help='c', nargs='?'),2532 ]2533 argument_group_signatures = [2534 (Sig('group'), [2535 Sig('-y', nargs='?', help='y'),2536 Sig('-z', nargs=3, help='z'),2537 Sig('d', help='d', nargs='*'),2538 Sig('e', help='e', nargs='+'),2539 ])2540 ]2541 usage = '''\2542 usage: PROG [-h] [-w W [W ...]] [-x [X [X ...]]] [-y [Y]] [-z Z Z Z]2543 a b b [c] [d [d ...]] e [e ...]2544 '''2545 help = usage + '''\2546 positional arguments:2547 a a2548 b b2549 c c2550 optional arguments:2551 -h, --help show this help message and exit2552 -w W [W ...] w2553 -x [X [X ...]] x2554 group:2555 -y [Y] y2556 -z Z Z Z z2557 d d2558 e e2559 '''2560 version = ''2561class TestHelpOnlyUserGroups(HelpTestCase):2562 """Test basic usage messages"""2563 parser_signature = Sig(prog='PROG', add_help=False)2564 argument_signatures = []2565 argument_group_signatures = [2566 (Sig('xxxx'), [2567 Sig('-x', help='x'),2568 Sig('a', help='a'),2569 ]),2570 (Sig('yyyy'), [2571 Sig('b', help='b'),2572 Sig('-y', help='y'),2573 ]),2574 ]2575 usage = '''\2576 usage: PROG [-x X] [-y Y] a b2577 '''2578 help = usage + '''\2579 xxxx:2580 -x X x2581 a a2582 yyyy:2583 b b2584 -y Y y2585 '''2586 version = ''2587class TestHelpUsageLongProg(HelpTestCase):2588 """Test usage messages where the prog is long"""2589 parser_signature = Sig(prog='P' * 60)2590 argument_signatures = [2591 Sig('-w', metavar='W'),2592 Sig('-x', metavar='X'),2593 Sig('a'),2594 Sig('b'),2595 ]2596 argument_group_signatures = []2597 usage = '''\2598 usage: PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP2599 [-h] [-w W] [-x X] a b2600 '''2601 help = usage + '''\2602 positional arguments:2603 a2604 b2605 optional arguments:2606 -h, --help show this help message and exit2607 -w W2608 -x X2609 '''2610 version = ''2611class TestHelpUsageLongProgOptionsWrap(HelpTestCase):2612 """Test usage messages where the prog is long and the optionals wrap"""2613 parser_signature = Sig(prog='P' * 60)2614 argument_signatures = [2615 Sig('-w', metavar='W' * 25),2616 Sig('-x', metavar='X' * 25),2617 Sig('-y', metavar='Y' * 25),2618 Sig('-z', metavar='Z' * 25),2619 Sig('a'),2620 Sig('b'),2621 ]2622 argument_group_signatures = []2623 usage = '''\2624 usage: PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP2625 [-h] [-w WWWWWWWWWWWWWWWWWWWWWWWWW] \2626[-x XXXXXXXXXXXXXXXXXXXXXXXXX]2627 [-y YYYYYYYYYYYYYYYYYYYYYYYYY] [-z ZZZZZZZZZZZZZZZZZZZZZZZZZ]2628 a b2629 '''2630 help = usage + '''\2631 positional arguments:2632 a2633 b2634 optional arguments:2635 -h, --help show this help message and exit2636 -w WWWWWWWWWWWWWWWWWWWWWWWWW2637 -x XXXXXXXXXXXXXXXXXXXXXXXXX2638 -y YYYYYYYYYYYYYYYYYYYYYYYYY2639 -z ZZZZZZZZZZZZZZZZZZZZZZZZZ2640 '''2641 version = ''2642class TestHelpUsageLongProgPositionalsWrap(HelpTestCase):2643 """Test usage messages where the prog is long and the positionals wrap"""2644 parser_signature = Sig(prog='P' * 60, add_help=False)2645 argument_signatures = [2646 Sig('a' * 25),2647 Sig('b' * 25),2648 Sig('c' * 25),2649 ]2650 argument_group_signatures = []2651 usage = '''\2652 usage: PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP2653 aaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbb2654 ccccccccccccccccccccccccc2655 '''2656 help = usage + '''\2657 positional arguments:2658 aaaaaaaaaaaaaaaaaaaaaaaaa2659 bbbbbbbbbbbbbbbbbbbbbbbbb2660 ccccccccccccccccccccccccc2661 '''2662 version = ''2663class TestHelpUsageOptionalsWrap(HelpTestCase):2664 """Test usage messages where the optionals wrap"""2665 parser_signature = Sig(prog='PROG')2666 argument_signatures = [2667 Sig('-w', metavar='W' * 25),2668 Sig('-x', metavar='X' * 25),2669 Sig('-y', metavar='Y' * 25),2670 Sig('-z', metavar='Z' * 25),2671 Sig('a'),2672 Sig('b'),2673 Sig('c'),2674 ]2675 argument_group_signatures = []2676 usage = '''\2677 usage: PROG [-h] [-w WWWWWWWWWWWWWWWWWWWWWWWWW] \2678[-x XXXXXXXXXXXXXXXXXXXXXXXXX]2679 [-y YYYYYYYYYYYYYYYYYYYYYYYYY] \2680[-z ZZZZZZZZZZZZZZZZZZZZZZZZZ]2681 a b c2682 '''2683 help = usage + '''\2684 positional arguments:2685 a2686 b2687 c2688 optional arguments:2689 -h, --help show this help message and exit2690 -w WWWWWWWWWWWWWWWWWWWWWWWWW2691 -x XXXXXXXXXXXXXXXXXXXXXXXXX2692 -y YYYYYYYYYYYYYYYYYYYYYYYYY2693 -z ZZZZZZZZZZZZZZZZZZZZZZZZZ2694 '''2695 version = ''2696class TestHelpUsagePositionalsWrap(HelpTestCase):2697 """Test usage messages where the positionals wrap"""2698 parser_signature = Sig(prog='PROG')2699 argument_signatures = [2700 Sig('-x'),2701 Sig('-y'),2702 Sig('-z'),2703 Sig('a' * 25),2704 Sig('b' * 25),2705 Sig('c' * 25),2706 ]2707 argument_group_signatures = []2708 usage = '''\2709 usage: PROG [-h] [-x X] [-y Y] [-z Z]2710 aaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbb2711 ccccccccccccccccccccccccc2712 '''2713 help = usage + '''\2714 positional arguments:2715 aaaaaaaaaaaaaaaaaaaaaaaaa2716 bbbbbbbbbbbbbbbbbbbbbbbbb2717 ccccccccccccccccccccccccc2718 optional arguments:2719 -h, --help show this help message and exit2720 -x X2721 -y Y2722 -z Z2723 '''2724 version = ''2725class TestHelpUsageOptionalsPositionalsWrap(HelpTestCase):2726 """Test usage messages where the optionals and positionals wrap"""2727 parser_signature = Sig(prog='PROG')2728 argument_signatures = [2729 Sig('-x', metavar='X' * 25),2730 Sig('-y', metavar='Y' * 25),2731 Sig('-z', metavar='Z' * 25),2732 Sig('a' * 25),2733 Sig('b' * 25),2734 Sig('c' * 25),2735 ]2736 argument_group_signatures = []2737 usage = '''\2738 usage: PROG [-h] [-x XXXXXXXXXXXXXXXXXXXXXXXXX] \2739[-y YYYYYYYYYYYYYYYYYYYYYYYYY]2740 [-z ZZZZZZZZZZZZZZZZZZZZZZZZZ]2741 aaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbb2742 ccccccccccccccccccccccccc2743 '''2744 help = usage + '''\2745 positional arguments:2746 aaaaaaaaaaaaaaaaaaaaaaaaa2747 bbbbbbbbbbbbbbbbbbbbbbbbb2748 ccccccccccccccccccccccccc2749 optional arguments:2750 -h, --help show this help message and exit2751 -x XXXXXXXXXXXXXXXXXXXXXXXXX2752 -y YYYYYYYYYYYYYYYYYYYYYYYYY2753 -z ZZZZZZZZZZZZZZZZZZZZZZZZZ2754 '''2755 version = ''2756class TestHelpUsageOptionalsOnlyWrap(HelpTestCase):2757 """Test usage messages where there are only optionals and they wrap"""2758 parser_signature = Sig(prog='PROG')2759 argument_signatures = [2760 Sig('-x', metavar='X' * 25),2761 Sig('-y', metavar='Y' * 25),2762 Sig('-z', metavar='Z' * 25),2763 ]2764 argument_group_signatures = []2765 usage = '''\2766 usage: PROG [-h] [-x XXXXXXXXXXXXXXXXXXXXXXXXX] \2767[-y YYYYYYYYYYYYYYYYYYYYYYYYY]2768 [-z ZZZZZZZZZZZZZZZZZZZZZZZZZ]2769 '''2770 help = usage + '''\2771 optional arguments:2772 -h, --help show this help message and exit2773 -x XXXXXXXXXXXXXXXXXXXXXXXXX2774 -y YYYYYYYYYYYYYYYYYYYYYYYYY2775 -z ZZZZZZZZZZZZZZZZZZZZZZZZZ2776 '''2777 version = ''2778class TestHelpUsagePositionalsOnlyWrap(HelpTestCase):2779 """Test usage messages where there are only positionals and they wrap"""2780 parser_signature = Sig(prog='PROG', add_help=False)2781 argument_signatures = [2782 Sig('a' * 25),2783 Sig('b' * 25),2784 Sig('c' * 25),2785 ]2786 argument_group_signatures = []2787 usage = '''\2788 usage: PROG aaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbb2789 ccccccccccccccccccccccccc2790 '''2791 help = usage + '''\2792 positional arguments:2793 aaaaaaaaaaaaaaaaaaaaaaaaa2794 bbbbbbbbbbbbbbbbbbbbbbbbb2795 ccccccccccccccccccccccccc2796 '''2797 version = ''2798class TestHelpVariableExpansion(HelpTestCase):2799 """Test that variables are expanded properly in help messages"""2800 parser_signature = Sig(prog='PROG')2801 argument_signatures = [2802 Sig('-x', type=int,2803 help='x %(prog)s %(default)s %(type)s %%'),2804 Sig('-y', action='store_const', default=42, const='XXX',2805 help='y %(prog)s %(default)s %(const)s'),2806 Sig('--foo', choices='abc',2807 help='foo %(prog)s %(default)s %(choices)s'),2808 Sig('--bar', default='baz', choices=[1, 2], metavar='BBB',2809 help='bar %(prog)s %(default)s %(dest)s'),2810 Sig('spam', help='spam %(prog)s %(default)s'),2811 Sig('badger', default=0.5, help='badger %(prog)s %(default)s'),2812 ]2813 argument_group_signatures = [2814 (Sig('group'), [2815 Sig('-a', help='a %(prog)s %(default)s'),2816 Sig('-b', default=-1, help='b %(prog)s %(default)s'),2817 ])2818 ]2819 usage = ('''\2820 usage: PROG [-h] [-x X] [-y] [--foo {a,b,c}] [--bar BBB] [-a A] [-b B]2821 spam badger2822 ''')2823 help = usage + '''\2824 positional arguments:2825 spam spam PROG None2826 badger badger PROG 0.52827 optional arguments:2828 -h, --help show this help message and exit2829 -x X x PROG None int %2830 -y y PROG 42 XXX2831 --foo {a,b,c} foo PROG None a, b, c2832 --bar BBB bar PROG baz bar2833 group:2834 -a A a PROG None2835 -b B b PROG -12836 '''2837 version = ''2838class TestHelpVariableExpansionUsageSupplied(HelpTestCase):2839 """Test that variables are expanded properly when usage= is present"""2840 parser_signature = Sig(prog='PROG', usage='%(prog)s FOO')2841 argument_signatures = []2842 argument_group_signatures = []2843 usage = ('''\2844 usage: PROG FOO2845 ''')2846 help = usage + '''\2847 optional arguments:2848 -h, --help show this help message and exit2849 '''2850 version = ''2851class TestHelpVariableExpansionNoArguments(HelpTestCase):2852 """Test that variables are expanded properly with no arguments"""2853 parser_signature = Sig(prog='PROG', add_help=False)2854 argument_signatures = []2855 argument_group_signatures = []2856 usage = ('''\2857 usage: PROG2858 ''')2859 help = usage2860 version = ''2861class TestHelpSuppressUsage(HelpTestCase):2862 """Test that items can be suppressed in usage messages"""2863 parser_signature = Sig(prog='PROG', usage=argparse.SUPPRESS)2864 argument_signatures = [2865 Sig('--foo', help='foo help'),2866 Sig('spam', help='spam help'),2867 ]2868 argument_group_signatures = []2869 help = '''\2870 positional arguments:2871 spam spam help2872 optional arguments:2873 -h, --help show this help message and exit2874 --foo FOO foo help2875 '''2876 usage = ''2877 version = ''2878class TestHelpSuppressOptional(HelpTestCase):2879 """Test that optional arguments can be suppressed in help messages"""2880 parser_signature = Sig(prog='PROG', add_help=False)2881 argument_signatures = [2882 Sig('--foo', help=argparse.SUPPRESS),2883 Sig('spam', help='spam help'),2884 ]2885 argument_group_signatures = []2886 usage = '''\2887 usage: PROG spam2888 '''2889 help = usage + '''\2890 positional arguments:2891 spam spam help2892 '''2893 version = ''2894class TestHelpSuppressOptionalGroup(HelpTestCase):2895 """Test that optional groups can be suppressed in help messages"""2896 parser_signature = Sig(prog='PROG')2897 argument_signatures = [2898 Sig('--foo', help='foo help'),2899 Sig('spam', help='spam help'),2900 ]2901 argument_group_signatures = [2902 (Sig('group'), [Sig('--bar', help=argparse.SUPPRESS)]),2903 ]2904 usage = '''\2905 usage: PROG [-h] [--foo FOO] spam2906 '''2907 help = usage + '''\2908 positional arguments:2909 spam spam help2910 optional arguments:2911 -h, --help show this help message and exit2912 --foo FOO foo help2913 '''2914 version = ''2915class TestHelpSuppressPositional(HelpTestCase):2916 """Test that positional arguments can be suppressed in help messages"""2917 parser_signature = Sig(prog='PROG')2918 argument_signatures = [2919 Sig('--foo', help='foo help'),2920 Sig('spam', help=argparse.SUPPRESS),2921 ]2922 argument_group_signatures = []2923 usage = '''\2924 usage: PROG [-h] [--foo FOO]2925 '''2926 help = usage + '''\2927 optional arguments:2928 -h, --help show this help message and exit2929 --foo FOO foo help2930 '''2931 version = ''2932class TestHelpRequiredOptional(HelpTestCase):2933 """Test that required options don't look optional"""2934 parser_signature = Sig(prog='PROG')2935 argument_signatures = [2936 Sig('--foo', required=True, help='foo help'),2937 ]2938 argument_group_signatures = []2939 usage = '''\2940 usage: PROG [-h] --foo FOO2941 '''2942 help = usage + '''\2943 optional arguments:2944 -h, --help show this help message and exit2945 --foo FOO foo help2946 '''2947 version = ''2948class TestHelpAlternatePrefixChars(HelpTestCase):2949 """Test that options display with different prefix characters"""2950 parser_signature = Sig(prog='PROG', prefix_chars='^;', add_help=False)2951 argument_signatures = [2952 Sig('^^foo', action='store_true', help='foo help'),2953 Sig(';b', ';;bar', help='bar help'),2954 ]2955 argument_group_signatures = []2956 usage = '''\2957 usage: PROG [^^foo] [;b BAR]2958 '''2959 help = usage + '''\2960 optional arguments:2961 ^^foo foo help2962 ;b BAR, ;;bar BAR bar help2963 '''2964 version = ''2965class TestHelpNoHelpOptional(HelpTestCase):2966 """Test that the --help argument can be suppressed help messages"""2967 parser_signature = Sig(prog='PROG', add_help=False)2968 argument_signatures = [2969 Sig('--foo', help='foo help'),2970 Sig('spam', help='spam help'),2971 ]2972 argument_group_signatures = []2973 usage = '''\2974 usage: PROG [--foo FOO] spam2975 '''2976 help = usage + '''\2977 positional arguments:2978 spam spam help2979 optional arguments:2980 --foo FOO foo help2981 '''2982 version = ''2983class TestHelpVersionOptional(HelpTestCase):2984 """Test that the --version argument can be suppressed help messages"""2985 parser_signature = Sig(prog='PROG', version='1.0')2986 argument_signatures = [2987 Sig('--foo', help='foo help'),2988 Sig('spam', help='spam help'),2989 ]2990 argument_group_signatures = []2991 usage = '''\2992 usage: PROG [-h] [-v] [--foo FOO] spam2993 '''2994 help = usage + '''\2995 positional arguments:2996 spam spam help2997 optional arguments:2998 -h, --help show this help message and exit2999 -v, --version show program's version number and exit3000 --foo FOO foo help3001 '''3002 version = '''\3003 1.03004 '''3005class TestHelpNone(HelpTestCase):3006 """Test that no errors occur if no help is specified"""3007 parser_signature = Sig(prog='PROG')3008 argument_signatures = [3009 Sig('--foo'),3010 Sig('spam'),3011 ]3012 argument_group_signatures = []3013 usage = '''\3014 usage: PROG [-h] [--foo FOO] spam3015 '''3016 help = usage + '''\3017 positional arguments:3018 spam3019 optional arguments:3020 -h, --help show this help message and exit3021 --foo FOO3022 '''3023 version = ''3024class TestHelpTupleMetavar(HelpTestCase):3025 """Test specifying metavar as a tuple"""3026 parser_signature = Sig(prog='PROG')3027 argument_signatures = [3028 Sig('-w', help='w', nargs='+', metavar=('W1', 'W2')),3029 Sig('-x', help='x', nargs='*', metavar=('X1', 'X2')),3030 Sig('-y', help='y', nargs=3, metavar=('Y1', 'Y2', 'Y3')),3031 Sig('-z', help='z', nargs='?', metavar=('Z1', )),3032 ]3033 argument_group_signatures = []3034 usage = '''\3035 usage: PROG [-h] [-w W1 [W2 ...]] [-x [X1 [X2 ...]]] [-y Y1 Y2 Y3] \3036[-z [Z1]]3037 '''3038 help = usage + '''\3039 optional arguments:3040 -h, --help show this help message and exit3041 -w W1 [W2 ...] w3042 -x [X1 [X2 ...]] x3043 -y Y1 Y2 Y3 y3044 -z [Z1] z3045 '''3046 version = ''3047class TestHelpRawText(HelpTestCase):3048 """Test the RawTextHelpFormatter"""3049 parser_signature = Sig(3050 prog='PROG', formatter_class=argparse.RawTextHelpFormatter,3051 description='Keep the formatting\n'3052 ' exactly as it is written\n'3053 '\n'3054 'here\n')3055 argument_signatures = [3056 Sig('--foo', help=' foo help should also\n'3057 'appear as given here'),3058 Sig('spam', help='spam help'),3059 ]3060 argument_group_signatures = [3061 (Sig('title', description=' This text\n'3062 ' should be indented\n'3063 ' exactly like it is here\n'),3064 [Sig('--bar', help='bar help')]),3065 ]3066 usage = '''\3067 usage: PROG [-h] [--foo FOO] [--bar BAR] spam3068 '''3069 help = usage + '''\3070 Keep the formatting3071 exactly as it is written3072 here3073 positional arguments:3074 spam spam help3075 optional arguments:3076 -h, --help show this help message and exit3077 --foo FOO foo help should also3078 appear as given here3079 title:3080 This text3081 should be indented3082 exactly like it is here3083 --bar BAR bar help3084 '''3085 version = ''3086class TestHelpRawDescription(HelpTestCase):3087 """Test the RawTextHelpFormatter"""3088 parser_signature = Sig(3089 prog='PROG', formatter_class=argparse.RawDescriptionHelpFormatter,3090 description='Keep the formatting\n'3091 ' exactly as it is written\n'3092 '\n'3093 'here\n')3094 argument_signatures = [3095 Sig('--foo', help=' foo help should not\n'3096 ' retain this odd formatting'),3097 Sig('spam', help='spam help'),3098 ]3099 argument_group_signatures = [3100 (Sig('title', description=' This text\n'3101 ' should be indented\n'3102 ' exactly like it is here\n'),3103 [Sig('--bar', help='bar help')]),3104 ]3105 usage = '''\3106 usage: PROG [-h] [--foo FOO] [--bar BAR] spam3107 '''3108 help = usage + '''\3109 Keep the formatting3110 exactly as it is written3111 here3112 positional arguments:3113 spam spam help3114 optional arguments:3115 -h, --help show this help message and exit3116 --foo FOO foo help should not retain this odd formatting3117 title:3118 This text3119 should be indented3120 exactly like it is here3121 --bar BAR bar help3122 '''3123 version = ''3124class TestHelpArgumentDefaults(HelpTestCase):3125 """Test the ArgumentDefaultsHelpFormatter"""3126 parser_signature = Sig(3127 prog='PROG', formatter_class=argparse.ArgumentDefaultsHelpFormatter,3128 description='description')3129 argument_signatures = [3130 Sig('--foo', help='foo help - oh and by the way, %(default)s'),3131 Sig('--bar', action='store_true', help='bar help'),3132 Sig('spam', help='spam help'),3133 Sig('badger', nargs='?', default='wooden', help='badger help'),3134 ]3135 argument_group_signatures = [3136 (Sig('title', description='description'),3137 [Sig('--baz', type=int, default=42, help='baz help')]),3138 ]3139 usage = '''\3140 usage: PROG [-h] [--foo FOO] [--bar] [--baz BAZ] spam [badger]3141 '''3142 help = usage + '''\3143 description3144 positional arguments:3145 spam spam help3146 badger badger help (default: wooden)3147 optional arguments:3148 -h, --help show this help message and exit3149 --foo FOO foo help - oh and by the way, None3150 --bar bar help (default: False)3151 title:3152 description3153 --baz BAZ baz help (default: 42)3154 '''3155 version = ''3156class TestHelpVersionAction(HelpTestCase):3157 """Test the default help for the version action"""3158 parser_signature = Sig(prog='PROG', description='description')3159 argument_signatures = [Sig('-V', '--version', action='version', version='3.6')]3160 argument_group_signatures = []3161 usage = '''\3162 usage: PROG [-h] [-V]3163 '''3164 help = usage + '''\3165 description3166 optional arguments:3167 -h, --help show this help message and exit3168 -V, --version show program's version number and exit3169 '''3170 version = ''3171class TestHelpSubparsersOrdering(HelpTestCase):3172 """Test ordering of subcommands in help matches the code"""3173 parser_signature = Sig(prog='PROG',3174 description='display some subcommands',3175 version='0.1')3176 subparsers_signatures = [Sig(name=name)3177 for name in ('a', 'b', 'c', 'd', 'e')]3178 usage = '''\3179 usage: PROG [-h] [-v] {a,b,c,d,e} ...3180 '''3181 help = usage + '''\3182 display some subcommands3183 positional arguments:3184 {a,b,c,d,e}3185 optional arguments:3186 -h, --help show this help message and exit3187 -v, --version show program's version number and exit3188 '''3189 version = '''\3190 0.13191 '''3192class TestHelpSubparsersWithHelpOrdering(HelpTestCase):3193 """Test ordering of subcommands in help matches the code"""3194 parser_signature = Sig(prog='PROG',3195 description='display some subcommands',3196 version='0.1')3197 subcommand_data = (('a', 'a subcommand help'),3198 ('b', 'b subcommand help'),3199 ('c', 'c subcommand help'),3200 ('d', 'd subcommand help'),3201 ('e', 'e subcommand help'),3202 )3203 subparsers_signatures = [Sig(name=name, help=help)3204 for name, help in subcommand_data]3205 usage = '''\3206 usage: PROG [-h] [-v] {a,b,c,d,e} ...3207 '''3208 help = usage + '''\3209 display some subcommands3210 positional arguments:3211 {a,b,c,d,e}3212 a a subcommand help3213 b b subcommand help3214 c c subcommand help3215 d d subcommand help3216 e e subcommand help3217 optional arguments:3218 -h, --help show this help message and exit3219 -v, --version show program's version number and exit3220 '''3221 version = '''\3222 0.13223 '''3224# =====================================3225# Optional/Positional constructor tests3226# =====================================3227class TestInvalidArgumentConstructors(TestCase):3228 """Test a bunch of invalid Argument constructors"""3229 def assertTypeError(self, *args, **kwargs):3230 parser = argparse.ArgumentParser()3231 self.assertRaises(TypeError, parser.add_argument,3232 *args, **kwargs)3233 def assertValueError(self, *args, **kwargs):3234 parser = argparse.ArgumentParser()3235 self.assertRaises(ValueError, parser.add_argument,3236 *args, **kwargs)3237 def test_invalid_keyword_arguments(self):3238 self.assertTypeError('-x', bar=None)3239 self.assertTypeError('-y', callback='foo')3240 self.assertTypeError('-y', callback_args=())3241 self.assertTypeError('-y', callback_kwargs={})3242 def test_missing_destination(self):3243 self.assertTypeError()3244 for action in ['append', 'store']:3245 self.assertTypeError(action=action)3246 def test_invalid_option_strings(self):3247 self.assertValueError('--')3248 self.assertValueError('---')3249 def test_invalid_type(self):3250 self.assertValueError('--foo', type='int')3251 self.assertValueError('--foo', type=(int, float))3252 def test_invalid_action(self):3253 self.assertValueError('-x', action='foo')3254 self.assertValueError('foo', action='baz')3255 self.assertValueError('--foo', action=('store', 'append'))3256 parser = argparse.ArgumentParser()3257 try:3258 parser.add_argument("--foo", action="store-true")3259 except ValueError:3260 e = sys.exc_info()[1]3261 expected = 'unknown action'3262 msg = 'expected %r, found %r' % (expected, e)3263 self.assertTrue(expected in str(e), msg)3264 def test_multiple_dest(self):3265 parser = argparse.ArgumentParser()3266 parser.add_argument(dest='foo')3267 try:3268 parser.add_argument('bar', dest='baz')3269 except ValueError:3270 e = sys.exc_info()[1]3271 expected = 'dest supplied twice for positional argument'3272 msg = 'expected %r, found %r' % (expected, e)3273 self.assertTrue(expected in str(e), msg)3274 def test_no_argument_actions(self):3275 for action in ['store_const', 'store_true', 'store_false',3276 'append_const', 'count']:3277 for attrs in [dict(type=int), dict(nargs='+'),3278 dict(choices='ab')]:3279 self.assertTypeError('-x', action=action, **attrs)3280 def test_no_argument_no_const_actions(self):3281 # options with zero arguments3282 for action in ['store_true', 'store_false', 'count']:3283 # const is always disallowed3284 self.assertTypeError('-x', const='foo', action=action)3285 # nargs is always disallowed3286 self.assertTypeError('-x', nargs='*', action=action)3287 def test_more_than_one_argument_actions(self):3288 for action in ['store', 'append']:3289 # nargs=0 is disallowed3290 self.assertValueError('-x', nargs=0, action=action)3291 self.assertValueError('spam', nargs=0, action=action)3292 # const is disallowed with non-optional arguments3293 for nargs in [1, '*', '+']:3294 self.assertValueError('-x', const='foo',3295 nargs=nargs, action=action)3296 self.assertValueError('spam', const='foo',3297 nargs=nargs, action=action)3298 def test_required_const_actions(self):3299 for action in ['store_const', 'append_const']:3300 # nargs is always disallowed3301 self.assertTypeError('-x', nargs='+', action=action)3302 def test_parsers_action_missing_params(self):3303 self.assertTypeError('command', action='parsers')3304 self.assertTypeError('command', action='parsers', prog='PROG')3305 self.assertTypeError('command', action='parsers',3306 parser_class=argparse.ArgumentParser)3307 def test_required_positional(self):3308 self.assertTypeError('foo', required=True)3309 def test_user_defined_action(self):3310 class Success(Exception):3311 pass3312 class Action(object):3313 def __init__(self,3314 option_strings,3315 dest,3316 const,3317 default,3318 required=False):3319 if dest == 'spam':3320 if const is Success:3321 if default is Success:3322 raise Success()3323 def __call__(self, *args, **kwargs):3324 pass3325 parser = argparse.ArgumentParser()3326 self.assertRaises(Success, parser.add_argument, '--spam',3327 action=Action, default=Success, const=Success)3328 self.assertRaises(Success, parser.add_argument, 'spam',3329 action=Action, default=Success, const=Success)3330# ================================3331# Actions returned by add_argument3332# ================================3333class TestActionsReturned(TestCase):3334 def test_dest(self):3335 parser = argparse.ArgumentParser()3336 action = parser.add_argument('--foo')3337 self.assertEqual(action.dest, 'foo')3338 action = parser.add_argument('-b', '--bar')3339 self.assertEqual(action.dest, 'bar')3340 action = parser.add_argument('-x', '-y')3341 self.assertEqual(action.dest, 'x')3342 def test_misc(self):3343 parser = argparse.ArgumentParser()3344 action = parser.add_argument('--foo', nargs='?', const=42,3345 default=84, type=int, choices=[1, 2],3346 help='FOO', metavar='BAR', dest='baz')3347 self.assertEqual(action.nargs, '?')3348 self.assertEqual(action.const, 42)3349 self.assertEqual(action.default, 84)3350 self.assertEqual(action.type, int)3351 self.assertEqual(action.choices, [1, 2])3352 self.assertEqual(action.help, 'FOO')3353 self.assertEqual(action.metavar, 'BAR')3354 self.assertEqual(action.dest, 'baz')3355# ================================3356# Argument conflict handling tests3357# ================================3358class TestConflictHandling(TestCase):3359 def test_bad_type(self):3360 self.assertRaises(ValueError, argparse.ArgumentParser,3361 conflict_handler='foo')3362 def test_conflict_error(self):3363 parser = argparse.ArgumentParser()3364 parser.add_argument('-x')3365 self.assertRaises(argparse.ArgumentError,3366 parser.add_argument, '-x')3367 parser.add_argument('--spam')3368 self.assertRaises(argparse.ArgumentError,3369 parser.add_argument, '--spam')3370 def test_resolve_error(self):3371 get_parser = argparse.ArgumentParser3372 parser = get_parser(prog='PROG', conflict_handler='resolve')3373 parser.add_argument('-x', help='OLD X')3374 parser.add_argument('-x', help='NEW X')3375 self.assertEqual(parser.format_help(), textwrap.dedent('''\3376 usage: PROG [-h] [-x X]3377 optional arguments:3378 -h, --help show this help message and exit3379 -x X NEW X3380 '''))3381 parser.add_argument('--spam', metavar='OLD_SPAM')3382 parser.add_argument('--spam', metavar='NEW_SPAM')3383 self.assertEqual(parser.format_help(), textwrap.dedent('''\3384 usage: PROG [-h] [-x X] [--spam NEW_SPAM]3385 optional arguments:3386 -h, --help show this help message and exit3387 -x X NEW X3388 --spam NEW_SPAM3389 '''))3390# =============================3391# Help and Version option tests3392# =============================3393class TestOptionalsHelpVersionActions(TestCase):3394 """Test the help and version actions"""3395 def _get_error(self, func, *args, **kwargs):3396 try:3397 func(*args, **kwargs)3398 except ArgumentParserError:3399 return sys.exc_info()[1]3400 else:3401 self.assertRaises(ArgumentParserError, func, *args, **kwargs)3402 def assertPrintHelpExit(self, parser, args_str):3403 self.assertEqual(3404 parser.format_help(),3405 self._get_error(parser.parse_args, args_str.split()).stdout)3406 def assertPrintVersionExit(self, parser, args_str):3407 self.assertEqual(3408 parser.format_version(),3409 self._get_error(parser.parse_args, args_str.split()).stderr)3410 def assertArgumentParserError(self, parser, *args):3411 self.assertRaises(ArgumentParserError, parser.parse_args, args)3412 def test_version(self):3413 parser = ErrorRaisingArgumentParser(version='1.0')3414 self.assertPrintHelpExit(parser, '-h')3415 self.assertPrintHelpExit(parser, '--help')3416 self.assertPrintVersionExit(parser, '-v')3417 self.assertPrintVersionExit(parser, '--version')3418 def test_version_format(self):3419 parser = ErrorRaisingArgumentParser(prog='PPP', version='%(prog)s 3.5')3420 msg = self._get_error(parser.parse_args, ['-v']).stderr3421 self.assertEqual('PPP 3.5\n', msg)3422 def test_version_no_help(self):3423 parser = ErrorRaisingArgumentParser(add_help=False, version='1.0')3424 self.assertArgumentParserError(parser, '-h')3425 self.assertArgumentParserError(parser, '--help')3426 self.assertPrintVersionExit(parser, '-v')3427 self.assertPrintVersionExit(parser, '--version')3428 def test_version_action(self):3429 parser = ErrorRaisingArgumentParser(prog='XXX')3430 parser.add_argument('-V', action='version', version='%(prog)s 3.7')3431 msg = self._get_error(parser.parse_args, ['-V']).stderr3432 self.assertEqual('XXX 3.7\n', msg)3433 def test_no_help(self):3434 parser = ErrorRaisingArgumentParser(add_help=False)3435 self.assertArgumentParserError(parser, '-h')3436 self.assertArgumentParserError(parser, '--help')3437 self.assertArgumentParserError(parser, '-v')3438 self.assertArgumentParserError(parser, '--version')3439 def test_alternate_help_version(self):3440 parser = ErrorRaisingArgumentParser()3441 parser.add_argument('-x', action='help')3442 parser.add_argument('-y', action='version')3443 self.assertPrintHelpExit(parser, '-x')3444 self.assertPrintVersionExit(parser, '-y')3445 self.assertArgumentParserError(parser, '-v')3446 self.assertArgumentParserError(parser, '--version')3447 def test_help_version_extra_arguments(self):...
app.py
Source:app.py
...48 #------------------------------------------------------------------------------49 if c.cmd == "args":50 if c.cmd2 == "help":51 from Naked.commands.args import help as args_help52 args_help()53 elif c.argc > 0: # there is an argument to where that is not help54 from Naked.commands.args import Args55 a = Args(c.arg_to_cmd)56 a.run()57 else:58 stderr("The args command requires an example command as an argument. Use 'naked args help' for more information.", 1)59 #------------------------------------------------------------------------------60 # [ build ] - build the C code in the Naked library (2)= help61 #------------------------------------------------------------------------------62 elif c.cmd == "build":63 if c.cmd2 == "help":64 from Naked.commands.build import help as build_help65 build_help()66 else:67 from Naked.commands.build import compile_c_code68 import os, inspect69 abs_dirpath = os.path.join(os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))), "toolshed", "c")70 compile_c_code(abs_dirpath) # function calls exit status code71 #------------------------------------------------------------------------------72 # [ classify ] - search Python application classifiers and display to user (args)-search string73 #------------------------------------------------------------------------------74 elif c.cmd == "classify":75 if c.cmd2 == "help":76 from Naked.commands.classifier import help as classifier_help77 classifier_help()78 else:79 if c.second: # if search string was given80 search_string = c.second81 else:82 search_string = "" # absence of search string detected in Classifier, defaults to the entire list instead of search83 from Naked.commands.classifier import Classifier84 c = Classifier(search_string)85 c.run()86 #------------------------------------------------------------------------------87 # [ dist ] - distribute source files to PyPI (2)=register, sdist, swheel, wheel, win, all, help88 #------------------------------------------------------------------------------89 elif c.cmd == "dist":90 if c.argc > 1:91 from Naked.commands.dist import Dist92 d = Dist()93 if c.cmd2 == "register": # python setup.py register94 d.run('register')95 elif c.cmd2 == "sdist": # python setup.py sdist upload96 d.run('sdist')97 elif c.cmd2 == "swheel": # python setup.py sdist bdist_wheel upload98 d.run('swheel')99 elif c.cmd2 == "wheel": # python setup.py bdist_wheel upload100 d.run('wheel')101 elif c.cmd2 == "win": # python setup.py bdist_wininst upload102 d.run('win')103 elif c.cmd2 == "all": # python setup.py sdist bdist_wheel bdist_wininst upload104 d.run('all')105 elif c.cmd2 == "help": # help for command106 from Naked.commands.dist import help as dist_help107 dist_help()108 else:109 stderr("The naked dist secondary command was not recognized. Use 'naked dist help' for more information.", 1)110 else:111 stderr("Please enter a secondary command", 1)112 #------------------------------------------------------------------------------113 # [ locate ] - locate Naked project files (2)= main, settings, setup, help114 #------------------------------------------------------------------------------115 elif c.cmd == "locate":116 from Naked.commands.locate import Locator117 if c.cmd2 == "help":118 from Naked.commands.locate import help as locate_help119 locate_help()120 elif c.cmd2 == "main":121 l = Locator('main')122 elif c.cmd2 == "settings":123 l = Locator('settings')124 elif c.cmd2 == "setup":125 l = Locator('setup')126 else:127 l = Locator('') #handles error report to user128 #------------------------------------------------------------------------------129 # [ make ] - make a new Naked project (2)=help (args)=project name130 #------------------------------------------------------------------------------131 elif c.cmd == "make":132 from Naked.commands.make import MakeController133 if c.cmd2 == "help":134 from Naked.commands.make import help as make_help135 make_help()136 if c.arg1: # arg1 is not help so use it as the argument to the make command137 m = MakeController(c.arg1)138 else:139 m = MakeController(None)140 m.run()141 #------------------------------------------------------------------------------142 # [ profile ] - run the profiler.py file in the Naked project (2)=help143 #------------------------------------------------------------------------------144 elif c.cmd == "profile":145 if c.cmd2 == "help":146 from Naked.commands.profile import help as profile_help147 profile_help()148 else:149 from Naked.commands.profile import Profiler150 p = Profiler()151 p.run()152 #------------------------------------------------------------------------------153 # [ pyh ] - help for python built-in library modules, classes, methods, functions154 #------------------------------------------------------------------------------155 elif c.cmd == "pyh":156 if c.cmd2 == "help":157 from Naked.commands.pyh import pyh_help158 pyh_help()159 else:160 if c.argc > 1:161 from Naked.commands.pyh import python_help162 python_help(c.arg1)163 else:164 stderr("Please enter a query term with the pyh command. Use 'naked pyh help' for more information.", 1)165 #------------------------------------------------------------------------------166 # [ test ] - Run unit tests on the project (2)= help,nose,pytest,tox,unittest (see help for args)167 #------------------------------------------------------------------------------168 elif c.cmd == "test":169 if c.argc > 1:170 if c.cmd2 == "help":171 from Naked.commands.test import help as tox_help172 tox_help()173 elif c.cmd2 == "nose":174 from Naked.commands.test import NoseTester175 n = NoseTester()176 n.run()177 elif c.cmd2 == "pytest":178 from Naked.commands.test import PyTester179 p = PyTester()180 p.run()181 elif c.cmd2 == "tox":182 from Naked.commands.test import ToxTester183 if c.arg2: #user specified a python version to run with one of the tox version defs184 t = ToxTester(c.arg2) #instantiate with the python version185 else:186 t = ToxTester()187 t.run()188 elif c.cmd2 == "unittest":189 from Naked.commands.test import UnitTester190 if c.arg2:191 t = UnitTester(c.arg2)192 t.run()193 else:194 stderr("Please include a unit test file path. Use 'naked test help' for more information.", 1)195 else:196 stderr("The secondary command was not recognized. Use 'naked test help' for more information.", 1)197 else:198 stderr("Please include a secondary command with the 'naked test' command. Use 'naked dist help' for more information.", 1)199 #------------------------------------------------------------------------------------------200 # [ NAKED FRAMEWORK COMMANDS ]201 # Naked framework provides default help, usage, and version commands for all applications202 # --> settings for user messages are assigned in the lib/PROJECT/settings.py file203 #------------------------------------------------------------------------------------------204 elif c.help(): # User requested naked help (help.py module in commands directory)205 from Naked.commands.help import Help206 Help().print_help()207 elif c.usage(): # user requested naked usage info (usage.py module in commands directory)208 from Naked.commands.usage import Usage209 Usage().print_usage()210 elif c.version(): # user requested naked version (version.py module in commands directory)211 from Naked.commands.version import Version212 Version().print_version()213 #------------------------------------------------------------------------------------------214 # [ DEFAULT MESSAGE FOR MATCH FAILURE ]215 # Message to provide to the user when all above conditional logic fails to meet a true condition216 #------------------------------------------------------------------------------------------217 else:218 print("Could not complete the command that you entered. Please try again.")219 sys.exit(1) #exit220if __name__ == '__main__':...
cmdoptions.py
Source:cmdoptions.py
1"""2shared options and groups3The principle here is to define options once, but *not* instantiate them globally.4One reason being that options with action='append' can carry state between parses.5pip parse's general options twice internally, and shouldn't pass on state.6To be consistent, all options will follow this design.7"""8import copy9from optparse import OptionGroup, SUPPRESS_HELP, Option10from pip.locations import build_prefix, default_log_file11def make_option_group(group, parser):12 """13 Return an OptionGroup object14 group -- assumed to be dict with 'name' and 'options' keys15 parser -- an optparse Parser16 """17 option_group = OptionGroup(parser, group['name'])18 for option in group['options']:19 option_group.add_option(option.make())20 return option_group21class OptionMaker(object):22 """Class that stores the args/kwargs that would be used to make an Option,23 for making them later, and uses deepcopy's to reset state."""24 def __init__(self, *args, **kwargs):25 self.args = args26 self.kwargs = kwargs27 def make(self):28 args_copy = copy.deepcopy(self.args)29 kwargs_copy = copy.deepcopy(self.kwargs)30 return Option(*args_copy, **kwargs_copy)31###########32# options #33###########34help_ = OptionMaker(35 '-h', '--help',36 dest='help',37 action='help',38 help='Show help.')39require_virtualenv = OptionMaker(40 # Run only if inside a virtualenv, bail if not.41 '--require-virtualenv', '--require-venv',42 dest='require_venv',43 action='store_true',44 default=False,45 help=SUPPRESS_HELP)46verbose = OptionMaker(47 '-v', '--verbose',48 dest='verbose',49 action='count',50 default=0,51 help='Give more output. Option is additive, and can be used up to 3 times.')52version = OptionMaker(53 '-V', '--version',54 dest='version',55 action='store_true',56 help='Show version and exit.')57quiet = OptionMaker(58 '-q', '--quiet',59 dest='quiet',60 action='count',61 default=0,62 help='Give less output.')63log = OptionMaker(64 '--log',65 dest='log',66 metavar='path',67 help='Path to a verbose appending log. This log is inactive by default.')68log_explicit_levels = OptionMaker(69 # Writes the log levels explicitely to the log'70 '--log-explicit-levels',71 dest='log_explicit_levels',72 action='store_true',73 default=False,74 help=SUPPRESS_HELP)75log_file = OptionMaker(76 # The default log file77 '--log-file', '--local-log',78 dest='log_file',79 metavar='path',80 default=default_log_file,81 help='Path to a verbose non-appending log, that only logs failures. This log is active by default at %default.')82no_input = OptionMaker(83 # Don't ask for input84 '--no-input',85 dest='no_input',86 action='store_true',87 default=False,88 help=SUPPRESS_HELP)89proxy = OptionMaker(90 '--proxy',91 dest='proxy',92 type='str',93 default='',94 help="Specify a proxy in the form [user:passwd@]proxy.server:port.")95timeout = OptionMaker(96 '--timeout', '--default-timeout',97 metavar='sec',98 dest='timeout',99 type='float',100 default=15,101 help='Set the socket timeout (default %default seconds).')102default_vcs = OptionMaker(103 # The default version control system for editables, e.g. 'svn'104 '--default-vcs',105 dest='default_vcs',106 type='str',107 default='',108 help=SUPPRESS_HELP)109skip_requirements_regex = OptionMaker(110 # A regex to be used to skip requirements111 '--skip-requirements-regex',112 dest='skip_requirements_regex',113 type='str',114 default='',115 help=SUPPRESS_HELP)116exists_action = OptionMaker(117 # Option when path already exist118 '--exists-action',119 dest='exists_action',120 type='choice',121 choices=['s', 'i', 'w', 'b'],122 default=[],123 action='append',124 metavar='action',125 help="Default action when a path already exists: "126 "(s)witch, (i)gnore, (w)ipe, (b)ackup.")127cert = OptionMaker(128 '--cert',129 dest='cert',130 type='str',131 default='',132 metavar='path',133 help = "Path to alternate CA bundle.")134index_url = OptionMaker(135 '-i', '--index-url', '--pypi-url',136 dest='index_url',137 metavar='URL',138 default='https://pypi.python.org/simple/',139 help='Base URL of Python Package Index (default %default).')140extra_index_url = OptionMaker(141 '--extra-index-url',142 dest='extra_index_urls',143 metavar='URL',144 action='append',145 default=[],146 help='Extra URLs of package indexes to use in addition to --index-url.')147no_index = OptionMaker(148 '--no-index',149 dest='no_index',150 action='store_true',151 default=False,152 help='Ignore package index (only looking at --find-links URLs instead).')153find_links = OptionMaker(154 '-f', '--find-links',155 dest='find_links',156 action='append',157 default=[],158 metavar='url',159 help="If a url or path to an html file, then parse for links to archives. If a local path or file:// url that's a directory, then look for archives in the directory listing.")160# TODO: Remove after 1.6161use_mirrors = OptionMaker(162 '-M', '--use-mirrors',163 dest='use_mirrors',164 action='store_true',165 default=False,166 help=SUPPRESS_HELP)167# TODO: Remove after 1.6168mirrors = OptionMaker(169 '--mirrors',170 dest='mirrors',171 metavar='URL',172 action='append',173 default=[],174 help=SUPPRESS_HELP)175allow_external = OptionMaker(176 "--allow-external",177 dest="allow_external",178 action="append",179 default=[],180 metavar="PACKAGE",181 help="Allow the installation of externally hosted files",182)183allow_all_external = OptionMaker(184 "--allow-all-external",185 dest="allow_all_external",186 action="store_true",187 default=False,188 help="Allow the installation of all externally hosted files",189)190# Remove after 1.7191no_allow_external = OptionMaker(192 "--no-allow-external",193 dest="allow_all_external",194 action="store_false",195 default=False,196 help=SUPPRESS_HELP,197)198# Remove --allow-insecure after 1.7199allow_unsafe = OptionMaker(200 "--allow-unverified", "--allow-insecure",201 dest="allow_unverified",202 action="append",203 default=[],204 metavar="PACKAGE",205 help="Allow the installation of insecure and unverifiable files",206)207# Remove after 1.7208no_allow_unsafe = OptionMaker(209 "--no-allow-insecure",210 dest="allow_all_insecure",211 action="store_false",212 default=False,213 help=SUPPRESS_HELP214)215# Remove after 1.5216process_dependency_links = OptionMaker(217 "--process-dependency-links",218 dest="process_dependency_links",219 action="store_true",220 default=False,221 help="Enable the processing of dependency links.",222)223requirements = OptionMaker(224 '-r', '--requirement',225 dest='requirements',226 action='append',227 default=[],228 metavar='file',229 help='Install from the given requirements file. '230 'This option can be used multiple times.')231use_wheel = OptionMaker(232 '--use-wheel',233 dest='use_wheel',234 action='store_true',235 help=SUPPRESS_HELP,236)237no_use_wheel = OptionMaker(238 '--no-use-wheel',239 dest='use_wheel',240 action='store_false',241 default=True,242 help=('Do not Find and prefer wheel archives when searching indexes and '243 'find-links locations.'),244)245download_cache = OptionMaker(246 '--download-cache',247 dest='download_cache',248 metavar='dir',249 default=None,250 help='Cache downloaded packages in <dir>.')251no_deps = OptionMaker(252 '--no-deps', '--no-dependencies',253 dest='ignore_dependencies',254 action='store_true',255 default=False,256 help="Don't install package dependencies.")257build_dir = OptionMaker(258 '-b', '--build', '--build-dir', '--build-directory',259 dest='build_dir',260 metavar='dir',261 default=build_prefix,262 help='Directory to unpack packages into and build in. '263 'The default in a virtualenv is "<venv path>/build". '264 'The default for global installs is "<OS temp dir>/pip_build_<username>".')265install_options = OptionMaker(266 '--install-option',267 dest='install_options',268 action='append',269 metavar='options',270 help="Extra arguments to be supplied to the setup.py install "271 "command (use like --install-option=\"--install-scripts=/usr/local/bin\"). "272 "Use multiple --install-option options to pass multiple options to setup.py install. "273 "If you are using an option with a directory path, be sure to use absolute path.")274global_options = OptionMaker(275 '--global-option',276 dest='global_options',277 action='append',278 metavar='options',279 help="Extra global options to be supplied to the setup.py "280 "call before the install command.")281no_clean = OptionMaker(282 '--no-clean',283 action='store_true',284 default=False,285 help="Don't clean up build directories.")286##########287# groups #288##########289general_group = {290 'name': 'General Options',291 'options': [292 help_,293 require_virtualenv,294 verbose,295 version,296 quiet,297 log_file,298 log,299 log_explicit_levels,300 no_input,301 proxy,302 timeout,303 default_vcs,304 skip_requirements_regex,305 exists_action,306 cert,307 ]308 }309index_group = {310 'name': 'Package Index Options',311 'options': [312 index_url,313 extra_index_url,314 no_index,315 find_links,316 use_mirrors,317 mirrors,318 allow_external,319 allow_all_external,320 no_allow_external,321 allow_unsafe,322 no_allow_unsafe,323 process_dependency_links,324 ]...
help.py
Source:help.py
1# -*- coding: utf-8 -*-2# Copyright 2011 Google Inc. All Rights Reserved.3#4# Licensed under the Apache License, Version 2.0 (the "License");5# you may not use this file except in compliance with the License.6# You may obtain a copy of the License at7#8# http://www.apache.org/licenses/LICENSE-2.09#10# Unless required by applicable law or agreed to in writing, software11# distributed under the License is distributed on an "AS IS" BASIS,12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13# See the License for the specific language governing permissions and14# limitations under the License.15"""Implementation of gsutil help command."""16from __future__ import absolute_import17import itertools18import os19import pkgutil20import re21from subprocess import PIPE22from subprocess import Popen23import gslib.addlhelp24from gslib.command import Command25from gslib.command import OLD_ALIAS_MAP26import gslib.commands27from gslib.exception import CommandException28from gslib.help_provider import HelpProvider29from gslib.help_provider import MAX_HELP_NAME_LEN30from gslib.util import IsRunningInteractively31_SYNOPSIS = """32 gsutil help [command or topic]33"""34_DETAILED_HELP_TEXT = ("""35<B>SYNOPSIS</B>36""" + _SYNOPSIS + """37<B>DESCRIPTION</B>38 Running:39 gsutil help40 will provide a summary of all commands and additional topics on which41 help is available.42 Running:43 gsutil help command or topic44 will provide help about the specified command or topic.45 Running:46 gsutil help command sub-command47 will provide help about the specified sub-command. For example, running:48 gsutil help acl set49 will provide help about the "set" subcommand of the "acl" command.50 If you set the PAGER environment variable to the path to a pager program51 (such as /bin/less on Linux), long help sections will be piped through52 the specified pager.53""")54top_level_usage_string = (55 'Usage: gsutil [-D] [-DD] [-h header]... '56 '[-m] [-o] [-q] [command [opts...] args...]'57)58class HelpCommand(Command):59 """Implementation of gsutil help command."""60 # Command specification. See base class for documentation.61 command_spec = Command.CreateCommandSpec(62 'help',63 command_name_aliases=['?', 'man'],64 usage_synopsis=_SYNOPSIS,65 min_args=0,66 max_args=2,67 supported_sub_args='',68 file_url_ok=True,69 provider_url_ok=False,70 urls_start_arg=0,71 )72 # Help specification. See help_provider.py for documentation.73 help_spec = Command.HelpSpec(74 help_name='help',75 help_name_aliases=['?'],76 help_type='command_help',77 help_one_line_summary='Get help about commands and topics',78 help_text=_DETAILED_HELP_TEXT,79 subcommand_help_text={},80 )81 def RunCommand(self):82 """Command entry point for the help command."""83 (help_type_map, help_name_map) = self._LoadHelpMaps()84 output = []85 if not self.args:86 output.append('%s\nAvailable commands:\n' % top_level_usage_string)87 format_str = ' %-' + str(MAX_HELP_NAME_LEN) + 's%s\n'88 for help_prov in sorted(help_type_map['command_help'],89 key=lambda hp: hp.help_spec.help_name):90 output.append(format_str % (91 help_prov.help_spec.help_name,92 help_prov.help_spec.help_one_line_summary))93 output.append('\nAdditional help topics:\n')94 for help_prov in sorted(help_type_map['additional_help'],95 key=lambda hp: hp.help_spec.help_name):96 output.append(format_str % (97 help_prov.help_spec.help_name,98 help_prov.help_spec.help_one_line_summary))99 output.append('\nUse gsutil help <command or topic> for detailed help.')100 else:101 invalid_subcommand = False102 arg = self.args[0]103 if arg not in help_name_map:104 output.append('No help available for "%s"' % arg)105 else:106 help_prov = help_name_map[arg]107 help_name = None108 if len(self.args) > 1: # We also have a subcommand argument.109 subcommand_map = help_prov.help_spec.subcommand_help_text110 if subcommand_map and self.args[1] in subcommand_map:111 help_name = arg + ' ' + self.args[1]112 help_text = subcommand_map[self.args[1]]113 else:114 invalid_subcommand = True115 if not subcommand_map:116 output.append((117 'The "%s" command has no subcommands. You can ask for the '118 'full help by running:\n\n\tgsutil help %s\n') %119 (arg, arg))120 else:121 subcommand_examples = []122 for subcommand in subcommand_map:123 subcommand_examples.append(124 '\tgsutil help %s %s' % (arg, subcommand))125 output.append(126 ('Subcommand "%s" does not exist for command "%s".\n'127 'You can either ask for the full help about the command by '128 'running:\n\n\tgsutil help %s\n\n'129 'Or you can ask for help about one of the subcommands:\n\n%s'130 ) % (self.args[1], arg, arg, '\n'.join(subcommand_examples)))131 if not invalid_subcommand:132 if not help_name: # No subcommand or invalid subcommand.133 help_name = help_prov.help_spec.help_name134 help_text = help_prov.help_spec.help_text135 output.append('<B>NAME</B>\n')136 output.append(' %s - %s\n' % (137 help_name, help_prov.help_spec.help_one_line_summary))138 output.append('\n\n')139 output.append(help_text.strip('\n'))140 new_alias = OLD_ALIAS_MAP.get(arg, [None])[0]141 if new_alias:142 deprecation_warning = """143 The "%s" alias is deprecated, and will eventually be removed completely.144 Please use the "%s" command instead.""" % (arg, new_alias)145 output.append('\n\n\n<B>DEPRECATION WARNING</B>\n')146 output.append(deprecation_warning)147 self._OutputHelp(''.join(output))148 return 0149 def _OutputHelp(self, help_str):150 """Outputs simply formatted string.151 This function paginates if the string is too long, PAGER is defined, and152 the output is a tty.153 Args:154 help_str: String to format.155 """156 # Replace <B> and </B> with terminal formatting strings if connected to tty.157 if not IsRunningInteractively():158 help_str = re.sub('<B>', '', help_str)159 help_str = re.sub('</B>', '', help_str)160 print help_str161 return162 help_str = re.sub('<B>', '\033[1m', help_str)163 help_str = re.sub('</B>', '\033[0;0m', help_str)164 num_lines = len(help_str.split('\n'))165 if 'PAGER' in os.environ and num_lines >= gslib.util.GetTermLines():166 # Use -r option for less to make bolding work right.167 pager = os.environ['PAGER'].split(' ')168 if pager[0].endswith('less'):169 pager.append('-r')170 try:171 Popen(pager, stdin=PIPE).communicate(input=help_str)172 except OSError, e:173 raise CommandException('Unable to open pager (%s): %s' %174 (' '.join(pager), e))175 else:176 print help_str177 def _LoadHelpMaps(self):178 """Returns tuple of help type and help name.179 help type is a dict with key: help type180 value: list of HelpProviders181 help name is a dict with key: help command name or alias182 value: HelpProvider183 Returns:184 (help type, help name)185 """186 # Import all gslib.commands submodules.187 for _, module_name, _ in pkgutil.iter_modules(gslib.commands.__path__):188 __import__('gslib.commands.%s' % module_name)189 # Import all gslib.addlhelp submodules.190 for _, module_name, _ in pkgutil.iter_modules(gslib.addlhelp.__path__):191 __import__('gslib.addlhelp.%s' % module_name)192 help_type_map = {}193 help_name_map = {}194 for s in gslib.help_provider.ALL_HELP_TYPES:195 help_type_map[s] = []196 # Only include HelpProvider subclasses in the dict.197 for help_prov in itertools.chain(198 HelpProvider.__subclasses__(), Command.__subclasses__()):199 if help_prov is Command:200 # Skip the Command base class itself; we just want its subclasses,201 # where the help command text lives (in addition to non-Command202 # HelpProviders, like naming.py).203 continue204 gslib.help_provider.SanityCheck(help_prov, help_name_map)205 help_name_map[help_prov.help_spec.help_name] = help_prov206 for help_name_aliases in help_prov.help_spec.help_name_aliases:207 help_name_map[help_name_aliases] = help_prov208 help_type_map[help_prov.help_spec.help_type].append(help_prov)...
arguments.py
Source:arguments.py
1# Copyright (c) 2018-present, Facebook, Inc.2# All rights reserved.3#4# This source code is licensed under the license found in the5# LICENSE file in the root directory of this source tree.6#7import argparse8def parse_args():9 parser = argparse.ArgumentParser(description='Training script')10 # General arguments11 parser.add_argument('-d', '--dataset', default='h36m', type=str, metavar='NAME', help='target dataset') # h36m or humaneva12 parser.add_argument('-k', '--keypoints', default='cpn_ft_h36m_dbb', type=str, metavar='NAME', help='2D detections to use')13 parser.add_argument('-str', '--subjects-train', default='S1,S5,S6,S7,S8', type=str, metavar='LIST',14 help='training subjects separated by comma')15 parser.add_argument('-ste', '--subjects-test', default='S9,S11', type=str, metavar='LIST', help='test subjects separated by comma')16 parser.add_argument('-sun', '--subjects-unlabeled', default='', type=str, metavar='LIST',17 help='unlabeled subjects separated by comma for self-supervision')18 parser.add_argument('-a', '--actions', default='*', type=str, metavar='LIST',19 help='actions to train/test on, separated by comma, or * for all')20 parser.add_argument('-c', '--checkpoint', default='checkpoint', type=str, metavar='PATH',21 help='checkpoint directory')22 parser.add_argument('--checkpoint-frequency', default=10, type=int, metavar='N',23 help='create a checkpoint every N epochs')24 parser.add_argument('-r', '--resume', default='', type=str, metavar='FILENAME',25 help='checkpoint to resume (file name)')26 parser.add_argument('--evaluate', default='', type=str, metavar='FILENAME', help='checkpoint to evaluate (file name)')27 parser.add_argument('--render', action='store_true', help='visualize a particular video')28 parser.add_argument('--by-subject', action='store_true', help='break down error by subject (on evaluation)')29 parser.add_argument('--export-training-curves', action='store_true', help='save training curves as .png images')30 # Model arguments31 parser.add_argument('-s', '--stride', default=1, type=int, metavar='N', help='chunk size to use during training')32 parser.add_argument('-e', '--epochs', default=60, type=int, metavar='N', help='number of training epochs')33 parser.add_argument('-b', '--batch-size', default=1024, type=int, metavar='N', help='batch size in terms of predicted frames')34 parser.add_argument('-drop', '--dropout', default=0.25, type=float, metavar='P', help='dropout probability')35 parser.add_argument('-lr', '--learning-rate', default=0.001, type=float, metavar='LR', help='initial learning rate')36 parser.add_argument('-lrd', '--lr-decay', default=0.95, type=float, metavar='LR', help='learning rate decay per epoch')37 parser.add_argument('-no-da', '--no-data-augmentation', dest='data_augmentation', action='store_false',38 help='disable train-time flipping')39 parser.add_argument('-no-tta', '--no-test-time-augmentation', dest='test_time_augmentation', action='store_false',40 help='disable test-time flipping')41 parser.add_argument('-arc', '--architecture', default='3,3,3', type=str, metavar='LAYERS', help='filter widths separated by comma')42 parser.add_argument('--causal', action='store_true', help='use causal convolutions for real-time processing')43 parser.add_argument('-ch', '--channels', default=1024, type=int, metavar='N', help='number of channels in convolution layers')44 # Experimental45 parser.add_argument('--subset', default=1, type=float, metavar='FRACTION', help='reduce dataset size by fraction')46 parser.add_argument('--downsample', default=1, type=int, metavar='FACTOR', help='downsample frame rate by factor (semi-supervised)')47 parser.add_argument('--warmup', default=1, type=int, metavar='N', help='warm-up epochs for semi-supervision')48 parser.add_argument('--no-eval', action='store_true', help='disable epoch evaluation while training (small speed-up)')49 parser.add_argument('--dense', action='store_true', help='use dense convolutions instead of dilated convolutions')50 parser.add_argument('--disable-optimizations', action='store_true', help='disable optimized model for single-frame predictions')51 parser.add_argument('--linear-projection', action='store_true', help='use only linear coefficients for semi-supervised projection')52 parser.add_argument('--no-bone-length', action='store_false', dest='bone_length_term',53 help='disable bone length term in semi-supervised settings')54 parser.add_argument('--no-proj', action='store_true', help='disable projection for semi-supervised setting')55 56 # Visualization57 parser.add_argument('--viz-subject', type=str, metavar='STR', help='subject to render')58 parser.add_argument('--viz-action', type=str, metavar='STR', help='action to render')59 parser.add_argument('--viz-camera', type=int, default=0, metavar='N', help='camera to render')60 parser.add_argument('--viz-video', type=str, metavar='PATH', help='path to input video')61 parser.add_argument('--viz-skip', type=int, default=0, metavar='N', help='skip first N frames of input video')62 parser.add_argument('--viz-output', type=str, metavar='PATH', help='output file name (.gif or .mp4)')63 parser.add_argument('--viz-export', type=str, metavar='PATH', help='output file name for coordinates')64 parser.add_argument('--viz-bitrate', type=int, default=3000, metavar='N', help='bitrate for mp4 videos')65 parser.add_argument('--viz-no-ground-truth', action='store_true', help='do not show ground-truth poses')66 parser.add_argument('--viz-limit', type=int, default=-1, metavar='N', help='only render first N frames')67 parser.add_argument('--viz-downsample', type=int, default=1, metavar='N', help='downsample FPS by a factor N')68 parser.add_argument('--viz-size', type=int, default=5, metavar='N', help='image size')69 70 parser.set_defaults(bone_length_term=True)71 parser.set_defaults(data_augmentation=True)72 parser.set_defaults(test_time_augmentation=True)73 74 args = parser.parse_args()75 # Check invalid configuration76 if args.resume and args.evaluate:77 print('Invalid flags: --resume and --evaluate cannot be set at the same time')78 exit()79 80 if args.export_training_curves and args.no_eval:81 print('Invalid flags: --export-training-curves and --no-eval cannot be set at the same time')82 exit()...
test_cmd.py
Source:test_cmd.py
...50 >>> mycmd.completenames("12")51 []52 >>> mycmd.completenames("help")53 ['help']54 Test for the function complete_help():55 >>> mycmd.complete_help("a")56 ['add']57 >>> mycmd.complete_help("he")58 ['help']59 >>> mycmd.complete_help("12")60 []61 >>> sorted(mycmd.complete_help(""))62 ['add', 'exit', 'help', 'shell']63 Test for the function do_help():64 >>> mycmd.do_help("testet")65 *** No help on testet66 >>> mycmd.do_help("add")67 help text for add68 >>> mycmd.onecmd("help add")69 help text for add70 >>> mycmd.do_help("")71 <BLANKLINE>72 Documented commands (type help <topic>):73 ========================================74 add help75 <BLANKLINE>76 Undocumented commands:77 ======================78 exit shell79 <BLANKLINE>80 Test for the function print_topics():81 >>> mycmd.print_topics("header", ["command1", "command2"], 2 ,10)82 header83 ======84 command185 command286 <BLANKLINE>87 Test for the function columnize():88 >>> mycmd.columnize([str(i) for i in range(20)])89 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 1990 >>> mycmd.columnize([str(i) for i in range(20)], 10)91 0 7 1492 1 8 1593 2 9 1694 3 10 1795 4 11 1896 5 12 1997 6 1398 This is an interactive test, put some commands in the cmdqueue attribute99 and let it execute100 This test includes the preloop(), postloop(), default(), emptyline(),101 parseline(), do_help() functions102 >>> mycmd.use_rawinput=0103 >>> mycmd.cmdqueue=["", "add", "add 4 5", "help", "help add","exit"]104 >>> mycmd.cmdloop()105 Hello from preloop106 help text for add107 *** invalid number of arguments108 9109 <BLANKLINE>110 Documented commands (type help <topic>):111 ========================================112 add help113 <BLANKLINE>114 Undocumented commands:115 ======================...
docevents.py
Source:docevents.py
1# Copyright 2012-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.2#3# Licensed under the Apache License, Version 2.0 (the "License"). You4# may not use this file except in compliance with the License. A copy of5# the License is located at6#7# http://aws.amazon.com/apache2.0/8#9# or in the "license" file accompanying this file. This file is10# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF11# ANY KIND, either express or implied. See the License for the specific12# language governing permissions and limitations under the License.13DOC_EVENTS = {14 'doc-breadcrumbs': '.%s',15 'doc-title': '.%s',16 'doc-description': '.%s',17 'doc-synopsis-start': '.%s',18 'doc-synopsis-option': '.%s.%s',19 'doc-synopsis-end': '.%s',20 'doc-options-start': '.%s',21 'doc-option': '.%s.%s',22 'doc-option-example': '.%s.%s',23 'doc-options-end': '.%s',24 'doc-examples': '.%s',25 'doc-output': '.%s',26 'doc-subitems-start': '.%s',27 'doc-subitem': '.%s.%s',28 'doc-subitems-end': '.%s',29 'doc-relateditems-start': '.%s',30 'doc-relateditem': '.%s.%s',31 'doc-relateditems-end': '.%s'32 }33def generate_events(session, help_command):34 # Now generate the documentation events35 session.emit('doc-breadcrumbs.%s' % help_command.event_class,36 help_command=help_command)37 session.emit('doc-title.%s' % help_command.event_class,38 help_command=help_command)39 session.emit('doc-description.%s' % help_command.event_class,40 help_command=help_command)41 session.emit('doc-synopsis-start.%s' % help_command.event_class,42 help_command=help_command)43 if help_command.arg_table:44 for arg_name in help_command.arg_table:45 # An argument can set an '_UNDOCUMENTED' attribute46 # to True to indicate a parameter that exists47 # but shouldn't be documented. This can be used48 # for backwards compatibility of deprecated arguments.49 if getattr(help_command.arg_table[arg_name],50 '_UNDOCUMENTED', False):51 continue52 session.emit(53 'doc-synopsis-option.%s.%s' % (help_command.event_class,54 arg_name),55 arg_name=arg_name, help_command=help_command)56 session.emit('doc-synopsis-end.%s' % help_command.event_class,57 help_command=help_command)58 session.emit('doc-options-start.%s' % help_command.event_class,59 help_command=help_command)60 if help_command.arg_table:61 for arg_name in help_command.arg_table:62 if getattr(help_command.arg_table[arg_name],63 '_UNDOCUMENTED', False):64 continue65 session.emit('doc-option.%s.%s' % (help_command.event_class,66 arg_name),67 arg_name=arg_name, help_command=help_command)68 session.emit('doc-option-example.%s.%s' %69 (help_command.event_class, arg_name),70 arg_name=arg_name, help_command=help_command)71 session.emit('doc-options-end.%s' % help_command.event_class,72 help_command=help_command)73 session.emit('doc-subitems-start.%s' % help_command.event_class,74 help_command=help_command)75 if help_command.command_table:76 for command_name in sorted(help_command.command_table.keys()):77 if hasattr(help_command.command_table[command_name],78 '_UNDOCUMENTED'):79 continue80 session.emit('doc-subitem.%s.%s'81 % (help_command.event_class, command_name),82 command_name=command_name,83 help_command=help_command)84 session.emit('doc-subitems-end.%s' % help_command.event_class,85 help_command=help_command)86 session.emit('doc-examples.%s' % help_command.event_class,87 help_command=help_command)88 session.emit('doc-output.%s' % help_command.event_class,89 help_command=help_command)90 session.emit('doc-relateditems-start.%s' % help_command.event_class,91 help_command=help_command)92 if help_command.related_items:93 for related_item in sorted(help_command.related_items):94 session.emit('doc-relateditem.%s.%s'95 % (help_command.event_class, related_item),96 help_command=help_command,97 related_item=related_item)98 session.emit('doc-relateditems-end.%s' % help_command.event_class,...
help_provider.py
Source:help_provider.py
1# Copyright 2012 Google Inc. All Rights Reserved.2#3# Licensed under the Apache License, Version 2.0 (the "License");4# you may not use this file except in compliance with the License.5# You may obtain a copy of the License at6#7# http://www.apache.org/licenses/LICENSE-2.08#9# Unless required by applicable law or agreed to in writing, software10# distributed under the License is distributed on an "AS IS" BASIS,11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12# See the License for the specific language governing permissions and13# limitations under the License.14from gslib.exception import CommandException15class HelpType(object):16 COMMAND_HELP = 'command_help'17 ADDITIONAL_HELP = 'additional_help'18ALL_HELP_TYPES = [HelpType.COMMAND_HELP, HelpType.ADDITIONAL_HELP]19# help_spec key constants.20HELP_NAME = 'help_name'21HELP_NAME_ALIASES = 'help_name_aliases'22HELP_TYPE = 'help_type'23HELP_ONE_LINE_SUMMARY = 'help_one_line_summary'24HELP_TEXT = 'help_text'25# Constants enforced by SanityCheck26MAX_HELP_NAME_LEN = 1527MIN_ONE_LINE_SUMMARY_LEN = 1028MAX_ONE_LINE_SUMMARY_LEN = 80 - MAX_HELP_NAME_LEN29REQUIRED_SPEC_KEYS = [HELP_NAME, HELP_NAME_ALIASES, HELP_TYPE,30 HELP_ONE_LINE_SUMMARY, HELP_TEXT]31class HelpProvider(object):32 """Interface for providing help."""33 # Each subclass must define the following map.34 help_spec = {35 # Name of command or auxiliary help info for which this help applies.36 HELP_NAME : None,37 # List of help name aliases.38 HELP_NAME_ALIASES : None,39 # HelpType.40 HELP_TYPE : None,41 # One line summary of this help.42 HELP_ONE_LINE_SUMMARY : None,43 # The full help text.44 HELP_TEXT : None,45 }46# This is a static helper instead of a class method because the help loader47# (gslib.commands.help._LoadHelpMaps()) operates on classes not instances.48def SanityCheck(help_provider, help_name_map):49 """Helper for checking that a HelpProvider has minimally adequate content."""50 for k in REQUIRED_SPEC_KEYS:51 if k not in help_provider.help_spec or help_provider.help_spec[k] is None:52 raise CommandException('"%s" help implementation is missing %s '53 'specification' % (help_provider.help_name, k))54 # Sanity check the content.55 assert (len(help_provider.help_spec[HELP_NAME]) > 156 and len(help_provider.help_spec[HELP_NAME]) < MAX_HELP_NAME_LEN)57 for hna in help_provider.help_spec[HELP_NAME_ALIASES]:58 assert len(hna) > 059 one_line_summary_len = len(help_provider.help_spec[HELP_ONE_LINE_SUMMARY])60 assert (one_line_summary_len > MIN_ONE_LINE_SUMMARY_LEN61 and one_line_summary_len < MAX_ONE_LINE_SUMMARY_LEN)62 assert len(help_provider.help_spec[HELP_TEXT]) > 1063 # Ensure there are no dupe help names or aliases across commands.64 name_check_list = [help_provider.help_spec[HELP_NAME]]65 name_check_list.extend(help_provider.help_spec[HELP_NAME_ALIASES])66 for name_or_alias in name_check_list:67 if help_name_map.has_key(name_or_alias):68 raise CommandException(69 'Duplicate help name/alias "%s" found while loading help from %s. '70 'That name/alias was already taken by %s' % (name_or_alias,...
Using AI Code Generation
1const { help } = require('fast-check-monorepo');2help();3const { help } = require('fast-check-monorepo');4help();5const { help } = require('fast-check-monorepo');6help();7const { help } = require('fast-check-monorepo');8help();9- [help](#help)10- [run](#run)11const { help } = require('fast-check-monorepo');12help();13const { run } = require('fast-check-monorepo');14run();
Using AI Code Generation
1const { help } = require('fast-check');2const { gen } = require('./gen');3help(gen);4const { help } = require('fast-check');5const { gen } = require('./gen');6help(gen, { depth: 3 });7const { help } = require('fast-check');8const { gen } = require('./gen');9help(gen, { depth: 4 });10const { help } = require('fast-check');11const { gen } = require('./gen');12help(gen, { depth: 5 });13const { help } = require('fast-check');14const { gen } = require('./gen');15help(gen, { depth: 6 });16const { help } = require('fast-check');17const { gen } = require('./gen');18help(gen, { depth: 7 });19const { help } = require('fast-check');20const { gen } = require('./gen');21help(gen, { depth: 8 });22const { help } = require('fast-check');23const { gen } = require('./gen');24help(gen, { depth: 9 });
Using AI Code Generation
1const { help } = require('@dubzzz/fast-check');2const { run } = help();3function* gen() {4 yield 1;5 yield 2;6 yield 3;7}8run(gen);9const { help } = require('@dubzzz/fast-check');10const { run } = help();11function* gen() {12 yield 1;13 yield 2;14 yield 3;15}16run(gen);17const { help } = require('@dubzzz/fast-check');18const { run } = help();19function* gen() {20 yield 1;21 yield 2;22 yield 3;23}24run(gen);25const { help } = require('fast-check-monorepo');26const { run } = help();27function* gen() {28 yield 1;29 yield 2;30 yield 3;31}32run(gen);33### run(gen, config)34{35}36MIT © [dubzzz](
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!