Ticket #5989: examples-react-5989-4.patch

File examples-react-5989-4.patch, 8.8 KB (added by Richard Wall, 7 years ago)

Now with twisted.usage and other responses to the tom.prince revew.

  • doc/names/examples/dns-service.py

    === modified file 'doc/names/examples/dns-service.py'
     
    44# See LICENSE for details.
    55
    66"""
    7 USAGE: python dns-service.py SERVICE PROTO DOMAINNAME
     7Usage: dns-service.py SERVICE PROTO DOMAINNAME
    88
    99Print the SRV records for a given DOMAINNAME eg
    1010
     
    2121
    2222from twisted.names import client, error
    2323from twisted.internet.task import react
     24from twisted.python import usage
    2425
    2526
    2627def printResult(records, domainname):
     
    4849    sys.stderr.write('ERROR: domain name not found %r\n' % (domainname,))
    4950
    5051
     52class Options(usage.Options):
     53    synopsis = __doc__.strip()
     54    longdesc = ''
     55
     56    def parseArgs(self, service, proto, domainname):
     57        self['service'] = service
     58        self['proto'] = proto
     59        self['domainname'] = domainname
     60
     61
    5162def main(reactor, *argv):
     63    options = Options()
    5264    try:
    53         service, proto, domainname = sys.argv[1:]
    54     except ValueError:
     65        options.parseOptions(argv)
     66    except usage.UsageError as errortext:
    5567        sys.stderr.write(
    56             __doc__.lstrip() + '\n'
    57             'ERROR: incorrect command line arguments\n')
     68            __doc__.lstrip() + '\n')
     69        sys.stderr.write('ERROR: %s\n' % (errortext,))
    5870        raise SystemExit(1)
    5971
    6072    resolver = client.Resolver('/etc/resolv.conf')
    61     domainname = '_%s._%s.%s' % (service, proto, domainname)
     73    domainname = '_%(service)s._%(proto)s.%(domainname)s' % options
    6274    d = resolver.lookupService(domainname)
    6375    d.addCallback(printResult, domainname)
    6476    d.addErrback(printError, domainname)
  • doc/names/examples/gethostbyname.py

    === modified file 'doc/names/examples/gethostbyname.py'
     
    44# See LICENSE for details.
    55
    66"""
    7 USAGE: python gethostbyname.py HOSTNAME
     7Usage: gethostbyname.py HOSTNAME
    88
    99Print the IP address for a given hostname. eg
    1010
     
    2020
    2121from twisted.names import client, error
    2222from twisted.internet.task import react
     23from twisted.python import usage
    2324
    2425
    2526def printResult(address, hostname):
     
    4344    sys.stderr.write('ERROR: hostname not found %r\n' % (hostname,))
    4445
    4546
     47class Options(usage.Options):
     48    synopsis = __doc__.strip()
     49    longdesc = ''
     50
     51    def parseArgs(self, hostname):
     52        self['hostname'] = hostname
     53
     54
    4655def main(reactor, *argv):
     56    options = Options()
    4757    try:
    48         hostname = argv[0]
    49     except IndexError:
     58        options.parseOptions(argv)
     59    except usage.UsageError as errortext:
    5060        sys.stderr.write(
    51             __doc__.lstrip() + '\n'
    52             'ERROR: missing HOSTNAME argument\n')
     61            __doc__.lstrip() + '\n')
     62        sys.stderr.write('ERROR: %s\n' % (errortext,))
    5363        raise SystemExit(1)
    5464
     65    hostname = options['hostname']
    5566    d = client.getHostByName(hostname)
    5667    d.addCallback(printResult, hostname)
    5768    d.addErrback(printError, hostname)
  • doc/names/examples/testdns.py

    === modified file 'doc/names/examples/testdns.py'
     
    44# See LICENSE for details.
    55
    66"""
    7 USAGE: python testdns.py DOMAINNAME
     7Usage: testdns.py DOMAINNAME
    88
    99Print the Address records, Mail-Exchanger records and the Nameserver
    1010records for the given domain name. eg
     
    1616from twisted.internet import defer
    1717from twisted.internet.task import react
    1818from twisted.names import client, dns, error
     19from twisted.python import usage
    1920
    2021
    2122def formatRecords(records, heading):
     
    5455    sys.stderr.write('ERROR: domain name not found %r\n' % (domainname,))
    5556
    5657
     58class Options(usage.Options):
     59    synopsis = __doc__.strip()
     60    longdesc = ''
     61
     62    def parseArgs(self, domainname):
     63        self['domainname'] = domainname
     64
     65
    5766def main(reactor, *argv):
     67    options = Options()
    5868    try:
    59         domainname = argv[0]
    60     except IndexError:
     69        options.parseOptions(argv)
     70    except usage.UsageError as errortext:
    6171        sys.stderr.write(
    62             __doc__.lstrip() + '\n'
    63             'ERROR: missing DOMAINNAME argument\n')
     72            __doc__.lstrip() + '\n')
     73        sys.stderr.write('ERROR: %s\n' % (errortext,))
    6474        raise SystemExit(1)
    6575
     76    domainname = options['domainname']
    6677    r = client.Resolver('/etc/resolv.conf')
    6778    d = defer.gatherResults([
    6879            r.lookupAddress(domainname).addCallback(
  • twisted/names/test/test_examples.py

    === modified file 'twisted/names/test/test_examples.py'
     
    2828    features are added to it, and we want to test each one.
    2929    """
    3030
    31     examplePath = None
    32 
    3331    def setUp(self):
    3432        """
    3533        Add our example directory to the path and record which modules are
     
    3735        """
    3836        self.fakeErr = StringIO()
    3937        self.originalErr, sys.stderr = sys.stderr, self.fakeErr
     38        self.fakeOut = StringIO()
     39        self.originalOut, sys.stdout = sys.stdout, self.fakeOut
     40
    4041        self.originalPath = sys.path[:]
    4142        self.originalModules = sys.modules.copy()
     43
     44        # Get branch root
    4245        here = FilePath(__file__).parent().parent().parent().parent()
    43         for childName in self.examplePath:
     46
     47        # Find the example script within this branch
     48        for childName in self.exampleRelativePath.split('/'):
    4449            here = here.child(childName)
    45         if not here.exists():
    46             raise SkipTest(
    47                 "Examples (%s) not found - cannot test" % (here.path,))
    48         sys.path.append(here.parent().path)
     50            if not here.exists():
     51                raise SkipTest(
     52                    "Examples (%s) not found - cannot test" % (here.path,))
     53        self.examplePath = here
     54
     55        # Add the example parent folder to the Python path
     56        sys.path.append(self.examplePath.parent().path)
     57
    4958        # Import the example as a module
    50         moduleName = here.basename().split('.')[0]
     59        moduleName = self.examplePath.basename().split('.')[0]
    5160        self.example = __import__(moduleName)
    52         self.examplePath = here
    5361
    5462
    5563    def tearDown(self):
     
    7482
    7583    def test_usageConsistency(self):
    7684        """
     85        The example script prints a usage message to stdout if it is
     86        passed a --help option and then exits.
     87
     88        The first line should contain a USAGE summary, explaining the
     89        accepted command arguments.
     90        """
     91        # Pass None as first parameter - the reactor - it shouldn't
     92        # get as far as calling it.
     93        self.assertRaises(
     94            SystemExit, self.example.main, None, '--help')
     95
     96        out = self.fakeOut.getvalue().splitlines()
     97        self.assertTrue(
     98            out[0].startswith('Usage:'),
     99            'Usage message first line should start with "Usage:". '
     100            'Actual: %r' % (out[0],))
     101
     102
     103    def test_usageConsistencyOnError(self):
     104        """
    77105        The example script prints a usage message to stderr if it is
    78         passed unrecognised command line arguments.
     106        passed unrecognized command line arguments.
    79107
    80108        The first line should contain a USAGE summary, explaining the
    81109        accepted command arguments.
     
    83111        The last line should contain an ERROR summary, explaining that
    84112        incorrect arguments were supplied.
    85113        """
    86         self.assertRaises(SystemExit, self.example.main, None)
     114        # Pass None as first parameter - the reactor - it shouldn't
     115        # get as far as calling it.
     116        self.assertRaises(
     117            SystemExit, self.example.main, None, '--unexpected_argument')
     118
    87119        err = self.fakeErr.getvalue().splitlines()
    88120        self.assertTrue(
    89             err[0].startswith('USAGE:'),
    90             'Usage message first line should start with "USAGE:". '
     121            err[0].startswith('Usage:'),
     122            'Usage message first line should start with "Usage:". '
    91123            'Actual: %r' % (err[0],))
    92124        self.assertTrue(
    93125            err[-1].startswith('ERROR:'),
     
    101133    Test the testdns.py example script.
    102134    """
    103135
    104     examplePath = 'doc/names/examples/testdns.py'.split('/')
     136    exampleRelativePath = 'doc/names/examples/testdns.py'
    105137
    106138
    107139class GetHostByNameTests(ExampleTestBase, TestCase):
     
    109141    Test the gethostbyname.py example script.
    110142    """
    111143
    112     examplePath = 'doc/names/examples/gethostbyname.py'.split('/')
     144    exampleRelativePath = 'doc/names/examples/gethostbyname.py'
    113145
    114146
    115147class DnsServiceTests(ExampleTestBase, TestCase):
     
    117149    Test the dns-service.py example script.
    118150    """
    119151
    120     examplePath = 'doc/names/examples/dns-service.py'.split('/')
     152    exampleRelativePath = 'doc/names/examples/dns-service.py'