def test_completer(self): """ Completer produces zsh shell-code that produces no completion matches. """ c = usage.Completer() got = c._shellCode('some-option', usage._ZSH) self.assertEqual(got, ':some-option:') c = usage.Completer(descr='some action', repeat=True) got = c._shellCode('some-option', usage._ZSH) self.assertEqual(got, '*:some action:')
class ServerOptions(app.ServerOptions): synopsis = "Usage: twistd [options]" optFlags = [ ["nodaemon", "n", "don't daemonize, don't use default umask of 0077"], ["originalname", None, "Don't try to change the process name"], ["syslog", None, "Log to syslog, not to file"], [ "euid", "", "Set only effective user-id rather than real user-id. " "(This option has no effect unless the server is running as " "root, in which case it means not to shed all privileges " "after binding ports, retaining the option to regain " "privileges in cases such as spawning processes. " "Use with caution.)", ], ] optParameters = [ ["prefix", None, "twisted", "use the given prefix when syslogging"], ["pidfile", "", "twistd.pid", "Name of the pidfile"], ["chroot", None, None, "Chroot to a supplied directory before running"], ["uid", "u", None, "The uid to run as.", uidFromString], [ "gid", "g", None, "The gid to run as. If not specified, the default gid " "associated with the specified --uid is used.", gidFromString, ], ["umask", None, None, "The (octal) file creation mask to apply.", _umask], ] compData = usage.Completions( optActions={ "pidfile": usage.CompleteFiles("*.pid"), "chroot": usage.CompleteDirs(descr="chroot directory"), "gid": usage.CompleteGroups(descr="gid to run as"), "uid": usage.CompleteUsernames(descr="uid to run as"), "prefix": usage.Completer(descr="syslog prefix"), }, ) def opt_version(self): """ Print version information and exit. """ print( "twistd (the Twisted daemon) {}".format(copyright.version), file=self.stdout ) print(copyright.copyright, file=self.stdout) sys.exit() def postOptions(self): app.ServerOptions.postOptions(self) if self["pidfile"]: self["pidfile"] = os.path.abspath(self["pidfile"])
class ServerOptions(app.ServerOptions): synopsis = "Usage: twistd [options]" optFlags = [ ['nodaemon', 'n', "don't daemonize, don't use default umask of 0077"], ['originalname', None, "Don't try to change the process name"], ['syslog', None, "Log to syslog, not to file"], [ 'euid', '', "Set only effective user-id rather than real user-id. " "(This option has no effect unless the server is running as " "root, in which case it means not to shed all privileges " "after binding ports, retaining the option to regain " "privileges in cases such as spawning processes. " "Use with caution.)" ], ] optParameters = [ ['prefix', None, 'twisted', "use the given prefix when syslogging"], ['pidfile', '', 'twistd.pid', "Name of the pidfile"], [ 'chroot', None, None, 'Chroot to a supplied directory before running' ], ['uid', 'u', None, "The uid to run as.", uidFromString], ['gid', 'g', None, "The gid to run as.", gidFromString], [ 'umask', None, None, "The (octal) file creation mask to apply.", _umask ], ] compData = usage.Completions(optActions={ "pidfile": usage.CompleteFiles("*.pid"), "chroot": usage.CompleteDirs(descr="chroot directory"), "gid": usage.CompleteGroups(descr="gid to run as"), "uid": usage.CompleteUsernames(descr="uid to run as"), "prefix": usage.Completer(descr="syslog prefix"), }, ) def opt_version(self): """Print version information and exit. """ print 'twistd (the Twisted daemon) %s' % copyright.version print copyright.copyright sys.exit() def postOptions(self): app.ServerOptions.postOptions(self) if self['pidfile']: self['pidfile'] = os.path.abspath(self['pidfile'])
class _BasicOptions(object): """ Basic options shared between trial and its local workers. """ synopsis = """%s [options] [[file|package|module|TestCase|testmethod]...] """ % (os.path.basename(sys.argv[0]), ) longdesc = ("trial loads and executes a suite of unit tests, obtained " "from modules, packages and files listed on the command line.") optFlags = [ ["help", "h"], ["no-recurse", "N", "Don't recurse into packages"], ['help-orders', None, "Help on available test running orders"], [ 'help-reporters', None, "Help on available output plugins (reporters)" ], [ "rterrors", "e", "realtime errors, print out tracebacks as " "soon as they occur" ], ["unclean-warnings", None, "Turn dirty reactor errors into warnings"], [ "force-gc", None, "Have Trial run gc.collect() before and " "after each test case." ], [ "exitfirst", "x", "Exit after the first non-successful result (cannot be " "specified along with --jobs)." ], ] optParameters = [ [ "order", "o", None, "Specify what order to run test cases and methods. " "See --help-orders for more info.", _checkKnownRunOrder ], [ "random", "z", None, "Run tests in random order using the specified seed" ], [ 'temp-directory', None, '_trial_temp', 'Path to use as working directory for tests.' ], [ 'reporter', None, 'verbose', 'The reporter to use for this test run. See --help-reporters for ' 'more info.' ] ] compData = usage.Completions( optActions={ "order": usage.CompleteList(_runOrders), "reporter": _reporterAction, "logfile": usage.CompleteFiles(descr="log file name"), "random": usage.Completer(descr="random seed") }, extraActions=[ usage.CompleteFiles( "*.py", descr="file | module | package | TestCase | testMethod", repeat=True) ], ) fallbackReporter = reporter.TreeReporter tracer = None def __init__(self): self['tests'] = [] usage.Options.__init__(self) def coverdir(self): """ Return a L{FilePath} representing the directory into which coverage results should be written. """ coverdir = 'coverage' result = FilePath(self['temp-directory']).child(coverdir) print("Setting coverage directory to %s." % (result.path, )) return result # TODO: Some of the opt_* methods on this class have docstrings and some do # not. This is mostly because usage.Options's currently will replace # any intended output in optFlags and optParameters with the # docstring. See #6427. When that is fixed, all methods should be # given docstrings (and it should be verified that those with # docstrings already have content suitable for printing as usage # information). def opt_coverage(self): """ Generate coverage information in the coverage file in the directory specified by the temp-directory option. """ import trace self.tracer = trace.Trace(count=1, trace=0) sys.settrace(self.tracer.globaltrace) self['coverage'] = True def opt_testmodule(self, filename): """ Filename to grep for test cases (-*- test-case-name). """ # If the filename passed to this parameter looks like a test module # we just add that to the test suite. # # If not, we inspect it for an Emacs buffer local variable called # 'test-case-name'. If that variable is declared, we try to add its # value to the test suite as a module. # # This parameter allows automated processes (like Buildbot) to pass # a list of files to Trial with the general expectation of "these files, # whatever they are, will get tested" if not os.path.isfile(filename): sys.stderr.write("File %r doesn't exist\n" % (filename, )) return filename = os.path.abspath(filename) if isTestFile(filename): self['tests'].append(filename) else: self['tests'].extend(getTestModules(filename)) def opt_spew(self): """ Print an insanely verbose log of everything that happens. Useful when debugging freezes or locks in complex code. """ sys.settrace(spewer) def opt_help_orders(self): synopsis = ("Trial can attempt to run test cases and their methods in " "a few different orders. You can select any of the " "following options using --order=<foo>.\n") print(synopsis) for name, (description, _) in sorted(_runOrders.items()): print(' ', name, '\t', description) sys.exit(0) def opt_help_reporters(self): synopsis = ("Trial's output can be customized using plugins called " "Reporters. You can\nselect any of the following " "reporters using --reporter=<foo>\n") print(synopsis) for p in plugin.getPlugins(itrial.IReporter): print(' ', p.longOpt, '\t', p.description) sys.exit(0) def opt_disablegc(self): """ Disable the garbage collector """ self["disablegc"] = True gc.disable() def opt_tbformat(self, opt): """ Specify the format to display tracebacks with. Valid formats are 'plain', 'emacs', and 'cgitb' which uses the nicely verbose stdlib cgitb.text function """ try: self['tbformat'] = TBFORMAT_MAP[opt] except KeyError: raise usage.UsageError( "tbformat must be 'plain', 'emacs', or 'cgitb'.") def opt_recursionlimit(self, arg): """ see sys.setrecursionlimit() """ try: sys.setrecursionlimit(int(arg)) except (TypeError, ValueError): raise usage.UsageError( "argument to recursionlimit must be an integer") else: self["recursionlimit"] = int(arg) def opt_random(self, option): try: self['random'] = long(option) except ValueError: raise usage.UsageError( "Argument to --random must be a positive integer") else: if self['random'] < 0: raise usage.UsageError( "Argument to --random must be a positive integer") elif self['random'] == 0: self['random'] = long(time.time() * 100) def opt_without_module(self, option): """ Fake the lack of the specified modules, separated with commas. """ self["without-module"] = option for module in option.split(","): if module in sys.modules: warnings.warn("Module '%s' already imported, " "disabling anyway." % (module, ), category=RuntimeWarning) sys.modules[module] = None def parseArgs(self, *args): self['tests'].extend(args) def _loadReporterByName(self, name): for p in plugin.getPlugins(itrial.IReporter): qual = "%s.%s" % (p.module, p.klass) if p.longOpt == name: return reflect.namedAny(qual) raise usage.UsageError("Only pass names of Reporter plugins to " "--reporter. See --help-reporters for " "more info.") def postOptions(self): # Only load reporters now, as opposed to any earlier, to avoid letting # application-defined plugins muck up reactor selecting by importing # t.i.reactor and causing the default to be installed. self['reporter'] = self._loadReporterByName(self['reporter']) if 'tbformat' not in self: self['tbformat'] = 'default' if self['order'] is not None and self['random'] is not None: raise usage.UsageError( "You can't specify --random when using --order")
class ClientOptions(ConchOptions): synopsis = """Usage: conch [options] host [command] """ longdesc = ("conch is a SSHv2 client that allows logging into a remote " "machine and executing commands.") optParameters = [ ["escape", "e", "~"], [ "localforward", "L", None, "listen-port:host:port Forward local port to remote address", ], [ "remoteforward", "R", None, "listen-port:host:port Forward remote port to local address", ], ] optFlags = [ ["null", "n", "Redirect input from /dev/null."], ["fork", "f", "Fork to background after authentication."], ["tty", "t", "Tty; allocate a tty even if command is given."], ["notty", "T", "Do not allocate a tty."], ["noshell", "N", "Do not execute a shell or command."], ["subsystem", "s", "Invoke command (mandatory) as SSH2 subsystem."], ] compData = usage.Completions( mutuallyExclusive=[("tty", "notty")], optActions={ "localforward": usage.Completer(descr="listen-port:host:port"), "remoteforward": usage.Completer(descr="listen-port:host:port"), }, extraActions=[ usage.CompleteUserAtHost(), usage.Completer(descr="command"), usage.Completer(descr="argument", repeat=True), ], ) localForwards: List[Tuple[int, Tuple[int, int]]] = [] remoteForwards: List[Tuple[int, Tuple[int, int]]] = [] def opt_escape(self, esc): """ Set escape character; ``none'' = disable """ if esc == "none": self["escape"] = None elif esc[0] == "^" and len(esc) == 2: self["escape"] = chr(ord(esc[1]) - 64) elif len(esc) == 1: self["escape"] = esc else: sys.exit(f"Bad escape character '{esc}'.") def opt_localforward(self, f): """ Forward local port to remote address (lport:host:port) """ localPort, remoteHost, remotePort = f.split(":") # Doesn't do v6 yet localPort = int(localPort) remotePort = int(remotePort) self.localForwards.append((localPort, (remoteHost, remotePort))) def opt_remoteforward(self, f): """ Forward remote port to local address (rport:host:port) """ remotePort, connHost, connPort = f.split(":") # Doesn't do v6 yet remotePort = int(remotePort) connPort = int(connPort) self.remoteForwards.append((remotePort, (connHost, connPort))) def parseArgs(self, host, *command): self["host"] = host self["command"] = " ".join(command)
class ClientOptions(options.ConchOptions): synopsis = """Usage: conch [options] host [command] """ longdesc = ("conch is a SSHv2 client that allows logging into a remote " "machine and executing commands.") optParameters = [ ['escape', 'e', '~'], [ 'localforward', 'L', None, 'listen-port:host:port Forward local port to remote address' ], [ 'remoteforward', 'R', None, 'listen-port:host:port Forward remote port to local address' ], ] optFlags = [ ['null', 'n', 'Redirect input from /dev/null.'], ['fork', 'f', 'Fork to background after authentication.'], ['tty', 't', 'Tty; allocate a tty even if command is given.'], ['notty', 'T', 'Do not allocate a tty.'], ['noshell', 'N', 'Do not execute a shell or command.'], ['subsystem', 's', 'Invoke command (mandatory) as SSH2 subsystem.'], ] compData = usage.Completions( mutuallyExclusive=[("tty", "notty")], optActions={ "localforward": usage.Completer(descr="listen-port:host:port"), "remoteforward": usage.Completer(descr="listen-port:host:port") }, extraActions=[ usage.CompleteUserAtHost(), usage.Completer(descr="command"), usage.Completer(descr="argument", repeat=True) ]) localForwards = [] remoteForwards = [] def opt_escape(self, esc): """ Set escape character; ``none'' = disable """ if esc == 'none': self['escape'] = None elif esc[0] == '^' and len(esc) == 2: self['escape'] = chr(ord(esc[1]) - 64) elif len(esc) == 1: self['escape'] = esc else: sys.exit("Bad escape character '{}'.".format(esc)) def opt_localforward(self, f): """ Forward local port to remote address (lport:host:port) """ localPort, remoteHost, remotePort = f.split(':') # Doesn't do v6 yet localPort = int(localPort) remotePort = int(remotePort) self.localForwards.append((localPort, (remoteHost, remotePort))) def opt_remoteforward(self, f): """ Forward remote port to local address (rport:host:port) """ remotePort, connHost, connPort = f.split(':') # Doesn't do v6 yet remotePort = int(remotePort) connPort = int(connPort) self.remoteForwards.append((remotePort, (connHost, connPort))) def parseArgs(self, host, *command): self['host'] = host self['command'] = ' '.join(command)
class BrokenActions(usage.Options): compData = usage.Completions( extraActions=[usage.Completer(repeat=True), usage.Completer()])
class ConchOptions(usage.Options): optParameters = [ ['user', 'l', None, 'Log in using this user name.'], ['identity', 'i', None], ['ciphers', 'c', None], ['macs', 'm', None], [ 'port', 'p', None, 'Connect to this port. Server must be on the same port.' ], ['option', 'o', None, 'Ignored OpenSSH options'], ['host-key-algorithms', '', None], ['known-hosts', '', None, 'File to check for host keys'], [ 'user-authentications', '', None, 'Types of user authentications to use.' ], ['logfile', '', None, 'File to log to, or - for stdout'], ] # type: List[List[Optional[Union[str, int]]]] optFlags = [ ['version', 'V', 'Display version number only.'], ['compress', 'C', 'Enable compression.'], ['log', 'v', 'Enable logging (defaults to stderr)'], ['nox11', 'x', 'Disable X11 connection forwarding (default)'], ['agent', 'A', 'Enable authentication agent forwarding'], ['noagent', 'a', 'Disable authentication agent forwarding (default)'], [ 'reconnect', 'r', 'Reconnect to the server if the connection is lost.' ], ] compData = usage.Completions( mutuallyExclusive=[("agent", "noagent")], optActions={ "user": usage.CompleteUsernames(), "ciphers": usage.CompleteMultiList(SSHCiphers.cipherMap.keys(), descr='ciphers to choose from'), "macs": usage.CompleteMultiList(SSHCiphers.macMap.keys(), descr='macs to choose from'), "host-key-algorithms": usage.CompleteMultiList( SSHClientTransport.supportedPublicKeys, descr='host key algorithms to choose from'), #"user-authentications": usage.CompleteMultiList(? # descr='user authentication types' ), }, extraActions=[ usage.CompleteUserAtHost(), usage.Completer(descr="command"), usage.Completer(descr='argument', repeat=True) ]) def __init__(self, *args, **kw): usage.Options.__init__(self, *args, **kw) self.identitys = [] self.conns = None def opt_identity(self, i): """Identity for public-key authentication""" self.identitys.append(i) def opt_ciphers(self, ciphers): "Select encryption algorithms" ciphers = ciphers.split(',') for cipher in ciphers: if cipher not in SSHCiphers.cipherMap: sys.exit("Unknown cipher type '%s'" % cipher) self['ciphers'] = ciphers def opt_macs(self, macs): "Specify MAC algorithms" if isinstance(macs, unicode): macs = macs.encode("utf-8") macs = macs.split(b',') for mac in macs: if mac not in SSHCiphers.macMap: sys.exit("Unknown mac type '%r'" % mac) self['macs'] = macs def opt_host_key_algorithms(self, hkas): "Select host key algorithms" if isinstance(hkas, unicode): hkas = hkas.encode("utf-8") hkas = hkas.split(b',') for hka in hkas: if hka not in SSHClientTransport.supportedPublicKeys: sys.exit("Unknown host key type '%r'" % hka) self['host-key-algorithms'] = hkas def opt_user_authentications(self, uas): "Choose how to authenticate to the remote server" if isinstance(uas, unicode): uas = uas.encode("utf-8") self['user-authentications'] = uas.split(b',')
class GeneralOptions(usage.Options): synopsis = """Usage: tkconch [options] host [command] """ optParameters = [['user', 'l', None, 'Log in using this user name.'], ['identity', 'i', '~/.ssh/identity', 'Identity for public key authentication'], ['escape', 'e', '~', "Set escape character; ``none'' = disable"], ['cipher', 'c', None, 'Select encryption algorithm.'], ['macs', 'm', None, 'Specify MAC algorithms for protocol version 2.'], ['port', 'p', None, 'Connect to this port. Server must be on the same port.'], ['localforward', 'L', None, 'listen-port:host:port Forward local port to remote address'], ['remoteforward', 'R', None, 'listen-port:host:port Forward remote port to local address'], ] optFlags = [['tty', 't', 'Tty; allocate a tty even if command is given.'], ['notty', 'T', 'Do not allocate a tty.'], ['version', 'V', 'Display version number only.'], ['compress', 'C', 'Enable compression.'], ['noshell', 'N', 'Do not execute a shell or command.'], ['subsystem', 's', 'Invoke command (mandatory) as SSH2 subsystem.'], ['log', 'v', 'Log to stderr'], ['ansilog', 'a', 'Print the received data to stdout']] _ciphers = transport.SSHClientTransport.supportedCiphers _macs = transport.SSHClientTransport.supportedMACs compData = usage.Completions( mutuallyExclusive=[("tty", "notty")], optActions={ "cipher": usage.CompleteList(_ciphers), "macs": usage.CompleteList(_macs), "localforward": usage.Completer(descr="listen-port:host:port"), "remoteforward": usage.Completer(descr="listen-port:host:port")}, extraActions=[usage.CompleteUserAtHost(), usage.Completer(descr="command"), usage.Completer(descr="argument", repeat=True)] ) identitys = [] # type: List[str] localForwards = [] # type: List[Tuple[int, Tuple[int, int]]] remoteForwards = [] # type: List[Tuple[int, Tuple[int, int]]] def opt_identity(self, i): self.identitys.append(i) def opt_localforward(self, f): localPort, remoteHost, remotePort = f.split(':') # doesn't do v6 yet localPort = int(localPort) remotePort = int(remotePort) self.localForwards.append((localPort, (remoteHost, remotePort))) def opt_remoteforward(self, f): remotePort, connHost, connPort = f.split(':') # doesn't do v6 yet remotePort = int(remotePort) connPort = int(connPort) self.remoteForwards.append((remotePort, (connHost, connPort))) def opt_compress(self): SSHClientTransport.supportedCompressions[0:1] = ['zlib'] def parseArgs(self, *args): if args: self['host'] = args[0] self['command'] = ' '.join(args[1:]) else: self['host'] = '' self['command'] = ''
class GeneralOptions(usage.Options): synopsis = """Usage: tkconch [options] host [command] """ optParameters = [ ["user", "l", None, "Log in using this user name."], [ "identity", "i", "~/.ssh/identity", "Identity for public key authentication" ], ["escape", "e", "~", "Set escape character; ``none'' = disable"], ["cipher", "c", None, "Select encryption algorithm."], ["macs", "m", None, "Specify MAC algorithms for protocol version 2."], [ "port", "p", None, "Connect to this port. Server must be on the same port." ], [ "localforward", "L", None, "listen-port:host:port Forward local port to remote address", ], [ "remoteforward", "R", None, "listen-port:host:port Forward remote port to local address", ], ] optFlags = [ ["tty", "t", "Tty; allocate a tty even if command is given."], ["notty", "T", "Do not allocate a tty."], ["version", "V", "Display version number only."], ["compress", "C", "Enable compression."], ["noshell", "N", "Do not execute a shell or command."], ["subsystem", "s", "Invoke command (mandatory) as SSH2 subsystem."], ["log", "v", "Log to stderr"], ["ansilog", "a", "Print the received data to stdout"], ] _ciphers = transport.SSHClientTransport.supportedCiphers _macs = transport.SSHClientTransport.supportedMACs compData = usage.Completions( mutuallyExclusive=[("tty", "notty")], optActions={ "cipher": usage.CompleteList([v.decode() for v in _ciphers]), "macs": usage.CompleteList([v.decode() for v in _macs]), "localforward": usage.Completer(descr="listen-port:host:port"), "remoteforward": usage.Completer(descr="listen-port:host:port"), }, extraActions=[ usage.CompleteUserAtHost(), usage.Completer(descr="command"), usage.Completer(descr="argument", repeat=True), ], ) identitys: List[str] = [] localForwards: List[Tuple[int, Tuple[int, int]]] = [] remoteForwards: List[Tuple[int, Tuple[int, int]]] = [] def opt_identity(self, i): self.identitys.append(i) def opt_localforward(self, f): localPort, remoteHost, remotePort = f.split(":") # doesn't do v6 yet localPort = int(localPort) remotePort = int(remotePort) self.localForwards.append((localPort, (remoteHost, remotePort))) def opt_remoteforward(self, f): remotePort, connHost, connPort = f.split(":") # doesn't do v6 yet remotePort = int(remotePort) connPort = int(connPort) self.remoteForwards.append((remotePort, (connHost, connPort))) def opt_compress(self): SSHClientTransport.supportedCompressions[0:1] = ["zlib"] def parseArgs(self, *args): if args: self["host"] = args[0] self["command"] = " ".join(args[1:]) else: self["host"] = "" self["command"] = ""
class ConchOptions(usage.Options): optParameters: List[List[Optional[Union[str, int]]]] = [ ["user", "l", None, "Log in using this user name."], ["identity", "i", None], ["ciphers", "c", None], ["macs", "m", None], ["port", "p", None, "Connect to this port. Server must be on the same port."], ["option", "o", None, "Ignored OpenSSH options"], ["host-key-algorithms", "", None], ["known-hosts", "", None, "File to check for host keys"], ["user-authentications", "", None, "Types of user authentications to use."], ["logfile", "", None, "File to log to, or - for stdout"], ] optFlags = [ ["version", "V", "Display version number only."], ["compress", "C", "Enable compression."], ["log", "v", "Enable logging (defaults to stderr)"], ["nox11", "x", "Disable X11 connection forwarding (default)"], ["agent", "A", "Enable authentication agent forwarding"], ["noagent", "a", "Disable authentication agent forwarding (default)"], ["reconnect", "r", "Reconnect to the server if the connection is lost."], ] compData = usage.Completions( mutuallyExclusive=[("agent", "noagent")], optActions={ "user": usage.CompleteUsernames(), "ciphers": usage.CompleteMultiList( [v.decode() for v in SSHCiphers.cipherMap.keys()], descr="ciphers to choose from", ), "macs": usage.CompleteMultiList( [v.decode() for v in SSHCiphers.macMap.keys()], descr="macs to choose from", ), "host-key-algorithms": usage.CompleteMultiList( [v.decode() for v in SSHClientTransport.supportedPublicKeys], descr="host key algorithms to choose from", ), # "user-authentications": usage.CompleteMultiList(? # descr='user authentication types' ), }, extraActions=[ usage.CompleteUserAtHost(), usage.Completer(descr="command"), usage.Completer(descr="argument", repeat=True), ], ) def __init__(self, *args, **kw): usage.Options.__init__(self, *args, **kw) self.identitys = [] self.conns = None def opt_identity(self, i): """Identity for public-key authentication""" self.identitys.append(i) def opt_ciphers(self, ciphers): "Select encryption algorithms" ciphers = ciphers.split(",") for cipher in ciphers: if cipher not in SSHCiphers.cipherMap: sys.exit("Unknown cipher type '%s'" % cipher) self["ciphers"] = ciphers def opt_macs(self, macs): "Specify MAC algorithms" if isinstance(macs, str): macs = macs.encode("utf-8") macs = macs.split(b",") for mac in macs: if mac not in SSHCiphers.macMap: sys.exit("Unknown mac type '%r'" % mac) self["macs"] = macs def opt_host_key_algorithms(self, hkas): "Select host key algorithms" if isinstance(hkas, str): hkas = hkas.encode("utf-8") hkas = hkas.split(b",") for hka in hkas: if hka not in SSHClientTransport.supportedPublicKeys: sys.exit("Unknown host key type '%r'" % hka) self["host-key-algorithms"] = hkas def opt_user_authentications(self, uas): "Choose how to authenticate to the remote server" if isinstance(uas, str): uas = uas.encode("utf-8") self["user-authentications"] = uas.split(b",")
class Options(usage.Options, app.ReactorSelectionMixin): synopsis = """%s [options] [[file|package|module|TestCase|testmethod]...] """ % (os.path.basename(sys.argv[0]), ) longdesc = ("trial loads and executes a suite of unit tests, obtained " "from modules, packages and files listed on the command line.") optFlags = [ ["help", "h"], [ "rterrors", "e", "realtime errors, print out tracebacks as " "soon as they occur" ], [ "debug", "b", "Run tests in the Python debugger. Will load " "'.pdbrc' from current directory if it exists." ], [ "debug-stacktraces", "B", "Report Deferred creation and " "callback stack traces" ], [ "nopm", None, "don't automatically jump into debugger for " "postmorteming of exceptions" ], ["dry-run", 'n', "do everything but run the tests"], [ "force-gc", None, "Have Trial run gc.collect() before and " "after each test case." ], ["profile", None, "Run tests under the Python profiler"], ["unclean-warnings", None, "Turn dirty reactor errors into warnings"], ["until-failure", "u", "Repeat test until it fails"], ["no-recurse", "N", "Don't recurse into packages"], [ 'help-reporters', None, "Help on available output plugins (reporters)" ] ] optParameters = [ ["logfile", "l", "test.log", "log file name"], [ "random", "z", None, "Run tests in random order using the specified seed" ], [ 'temp-directory', None, '_trial_temp', 'Path to use as working directory for tests.' ], [ 'reporter', None, 'verbose', 'The reporter to use for this test run. See --help-reporters for ' 'more info.' ] ] compData = usage.Completions( optActions={ "tbformat": usage.CompleteList(["plain", "emacs", "cgitb"]), "reporter": _reporterAction, "logfile": usage.CompleteFiles(descr="log file name"), "random": usage.Completer(descr="random seed") }, extraActions=[ usage.CompleteFiles( "*.py", descr="file | module | package | TestCase | testMethod", repeat=True) ], ) fallbackReporter = reporter.TreeReporter extra = None tracer = None def __init__(self): self['tests'] = set() usage.Options.__init__(self) def coverdir(self): """ Return a L{FilePath} representing the directory into which coverage results should be written. """ coverdir = 'coverage' result = FilePath(self['temp-directory']).child(coverdir) print "Setting coverage directory to %s." % (result.path, ) return result def opt_coverage(self): """ Generate coverage information in the I{coverage} file in the directory specified by the I{trial-temp} option. """ import trace self.tracer = trace.Trace(count=1, trace=0) sys.settrace(self.tracer.globaltrace) def opt_testmodule(self, filename): """ Filename to grep for test cases (-*- test-case-name) """ # If the filename passed to this parameter looks like a test module # we just add that to the test suite. # # If not, we inspect it for an Emacs buffer local variable called # 'test-case-name'. If that variable is declared, we try to add its # value to the test suite as a module. # # This parameter allows automated processes (like Buildbot) to pass # a list of files to Trial with the general expectation of "these files, # whatever they are, will get tested" if not os.path.isfile(filename): sys.stderr.write("File %r doesn't exist\n" % (filename, )) return filename = os.path.abspath(filename) if isTestFile(filename): self['tests'].add(filename) else: self['tests'].update(getTestModules(filename)) def opt_spew(self): """ Print an insanely verbose log of everything that happens. Useful when debugging freezes or locks in complex code. """ sys.settrace(spewer) def opt_help_reporters(self): synopsis = ("Trial's output can be customized using plugins called " "Reporters. You can\nselect any of the following " "reporters using --reporter=<foo>\n") print synopsis for p in plugin.getPlugins(itrial.IReporter): print ' ', p.longOpt, '\t', p.description print sys.exit(0) def opt_disablegc(self): """ Disable the garbage collector """ gc.disable() def opt_tbformat(self, opt): """ Specify the format to display tracebacks with. Valid formats are 'plain', 'emacs', and 'cgitb' which uses the nicely verbose stdlib cgitb.text function """ try: self['tbformat'] = TBFORMAT_MAP[opt] except KeyError: raise usage.UsageError( "tbformat must be 'plain', 'emacs', or 'cgitb'.") def opt_extra(self, arg): """ Add an extra argument. (This is a hack necessary for interfacing with emacs's `gud'.) NOTE: This option is deprecated as of Twisted 11.0 """ warnings.warn(deprecate.getDeprecationWarningString( Options.opt_extra, versions.Version('Twisted', 11, 0, 0)), category=DeprecationWarning, stacklevel=2) if self.extra is None: self.extra = [] self.extra.append(arg) opt_x = opt_extra def opt_recursionlimit(self, arg): """ see sys.setrecursionlimit() """ try: sys.setrecursionlimit(int(arg)) except (TypeError, ValueError): raise usage.UsageError( "argument to recursionlimit must be an integer") def opt_random(self, option): try: self['random'] = long(option) except ValueError: raise usage.UsageError( "Argument to --random must be a positive integer") else: if self['random'] < 0: raise usage.UsageError( "Argument to --random must be a positive integer") elif self['random'] == 0: self['random'] = long(time.time() * 100) def opt_without_module(self, option): """ Fake the lack of the specified modules, separated with commas. """ for module in option.split(","): if module in sys.modules: warnings.warn("Module '%s' already imported, " "disabling anyway." % (module, ), category=RuntimeWarning) sys.modules[module] = None def parseArgs(self, *args): self['tests'].update(args) if self.extra is not None: self['tests'].update(self.extra) def _loadReporterByName(self, name): for p in plugin.getPlugins(itrial.IReporter): qual = "%s.%s" % (p.module, p.klass) if p.longOpt == name: return reflect.namedAny(qual) raise usage.UsageError("Only pass names of Reporter plugins to " "--reporter. See --help-reporters for " "more info.") def postOptions(self): # Only load reporters now, as opposed to any earlier, to avoid letting # application-defined plugins muck up reactor selecting by importing # t.i.reactor and causing the default to be installed. self['reporter'] = self._loadReporterByName(self['reporter']) if 'tbformat' not in self: self['tbformat'] = 'default' if self['nopm']: if not self['debug']: raise usage.UsageError("you must specify --debug when using " "--nopm ") failure.DO_POST_MORTEM = False