def smtpcli(argv): """smtpcli [-h] [-l <logfilename>] [-s <portname>] [host] [port] Provides an interactive session at a protocol level to an SMTP server. """ bindto = None port = 25 sourcefile = None paged = False logname = None try: optlist, longopts, args = getopt.getopt(argv[1:], "b:hp:s:l:g") except getopt.GetoptError: print(smtpcli.__doc__) return for opt, val in optlist: if opt == "-b": bindto = val if opt == "-l": logname = val elif opt == "-s": sourcefile = val elif opt == "-g": paged = True elif opt == "-h": print(smtpcli.__doc__) return elif opt == "-p": try: port = int(val) except ValueError: print(smtpcli.__doc__) return theme = UI.DefaultTheme(PROMPT) parser = CLI.get_cli(EmailClientCLI, paged=paged, theme=theme) if len(args) > 0: if len(args) > 1: port = int(args[1]) else: port = 25 host = args[0] else: host = "" if logname: parser.commands.logfile(["logfile", logname]) if host: parser.commands.connect(["connect"] + IF(bindto, ["-s", bindto], []) + [host, port]) else: parser.commands._print( "Be sure to run 'connect' before anything else.\n") if sourcefile: try: parser.parse(sourcefile) except CLI.CommandQuit: pass else: parser.interact()
def run(self, argv): """Run the test runner. Invoke the test runner by calling it. """ cf = self.runner.config cf.flags.INTERACTIVE = True cf.flags.DEBUG = 0 cf.flags.VERBOSE = 0 optlist, longopts, args = getopt.getopt(argv[1:], "h?dDvIc:f:m:e:r:") for opt, optarg in optlist: if opt in ("-h", "-?"): print(TestRunnerInterfaceDoc.format( name=os.path.basename(argv[0]))) return elif opt == "-d": cf.flags.DEBUG += 1 elif opt == "-D": from pycopia import autodebug # noqa elif opt == "-v": cf.flags.VERBOSE += 1 elif opt == "-I": cf.flags.INTERACTIVE = False elif opt == "-c" or opt == "-f": cf.mergefile(optarg) elif opt == "-m": cf.comment = optarg elif opt == "-r": cf.reportname = optarg elif opt == "-e": cf.environmentname = optarg cf.evalupdate(longopts) # original command line arguments saved for the report cf.arguments = [os.path.basename(argv[0])] + argv[1:] ui = UI.get_userinterface(themename="ANSITheme") if not args: from . import simplechooser args = simplechooser.choose_tests(ui) if not args: return 10 objects, errors = module.get_objects(args) if errors: logging.warn("Errors found while loading test object:") for error in errors: logging.warn(error) if objects: cf.argv = args rv = self.runner.run(objects, ui) if rv is None: return 11 else: try: return int(rv) except TypeError: return 12 else: return len(errors) + 20
def __init__(self, syslog, ps1="%Isyslog%N> "): self.syslog = syslog theme = UI.DefaultTheme(ps1) self.parser = CLI.get_cli(SyslogCLI, paged=False, theme=theme, aliases=_CMDALIASES) self.parser.command_setup(syslog, ps1)
def _build_userinterface(self): from pycopia import UI uitype = self.get("userinterfacetype", "default") params = self.userinterfaces.get(uitype) if params: params = self.expand_params(params) else: params = self.userinterfaces.get("default") return UI.get_userinterface(*params)
def choose_tests(): try: import testcases except ImportError: logging.warn("Cannot find 'testcases' base package.") return None from pycopia import UI from pycopia.QA import core ui = UI.get_userinterface(themename="ANSITheme") ui.printf( "Select any number of runnable objects. %n" "You can select %wmodules%N, %gUseCase%N objects, or single %yTest%N object." ) # callback for testdir walker def filternames(flist, dirname, names): for name in names: if name.endswith(".py") and not name.startswith("_"): flist.append(os.path.join(dirname, name[:-3])) modnames = [] runnables = [] for testbase in testcases.__path__: mnlist = [] os.path.walk(testbase, filternames, mnlist) testhome_index = len(os.path.dirname(testbase)) + 1 modnames.extend( map(lambda n: n[testhome_index:].replace("/", "."), mnlist)) modnames.sort() for modname in modnames: try: mod = module.get_module(modname) except module.ModuleImportError: ui.warning(" Warning: could not import '{}'".format(modname)) continue if getattr(mod, "run", None) is not None: runnables.append(FormatWrapper(ui, modname, None, "%w%U%N")) for attrname in dir(mod): obj = getattr(mod, attrname) if type(obj) is type: if issubclass(obj, core.UseCase): runnables.append( FormatWrapper(ui, modname, obj.__name__, "%U.%g%O%N")) if issubclass(obj, core.Test): runnables.append( FormatWrapper(ui, modname, obj.__name__, "%U.%y%O%N")) return [ o.fullname for o in ui.choose_multiple(runnables, prompt="Select tests") ]
def remotecli(argv): """remotecli [-h|-?] [-g] [-s <script>] Provides an interactive session to a remote Client server object. Most of the methods in the module remote.Server may be called this way. """ from pycopia import getopt from pycopia.storage import Storage paged = False script = None try: optlist, longopts, args = getopt.getopt(argv[1:], "s:?hg") except getopt.GetoptError: print remotecli.__doc__ return for opt, val in optlist: if opt == "-?" or opt == "-h": print remotecli.__doc__ return elif opt == "-g": paged = True elif opt == "-s": script = val # do runtime setup cf = Storage.get_config(initdict=longopts) #testrunner.connect_user(cf) #testrunner.runtime_config(cf) # fake test module attributes cf.reportfile = "remotecli" cf.logbasename = "remotecli.log" cf.arguments = argv theme = UI.DefaultTheme(PROMPT) history = os.path.expandvars("$HOME/.hist_clientcli") parser = CLI.get_cli(TopLevelCLI, env=cf, paged=paged, theme=theme, historyfile=history) if script: try: parser.parse(script) except KeyboardInterrupt: pass else: parser.interact()
def imapcli(argv): """imapcli [-h|--help] [-S] [host] [port] Provides an interactive session at a protocol level to an IMAP server. If the "-S" argument is provided, will connect using SSL. """ from pycopia import getopt port = imaplib.IMAP4_PORT sourcefile = None paged = False ssl = True try: optlist, longopts, args = getopt.getopt(argv[1:], "hp:s:gS") except getopt.GetoptError: print(imapcli.__doc__) return for opt, val in optlist: if opt == "-s": sourcefile = val elif opt == "-h": print(imapcli.__doc__) return elif opt == "-g": paged = True elif opt == "-S": ssl = True elif opt == "-p": try: port = int(val) except ValueError: print(imapcli.__doc__) return theme = UI.DefaultTheme(PROMPT) parser = CLI.get_cli(ImapCLI, paged=paged, theme=theme) if len(args) > 0: parser.commands.connect(["connect"] + ((ssl == True) and ["-S"] or []) + args) else: parser.commands._print( "Be sure to run 'connect' before anything else.\n") if sourcefile: try: parser.parse(sourcefile) except CLI.CommandQuit: pass else: parser.interact()
def unittest(argv): args = argv[1:] _init_db() tr = testrunner.TestRunner("sqlite://:memory:") ui = UI.get_userinterface(themename="ANSITheme") if not args: args = all_tests(ui) for tn in args: print(tn) return if not args: return objects, errors = module.get_objects(args) if errors: print("Errors found while loading test object:") for error in errors: print(error) if objects: tr.run(objects, ui)
def choose_tests(): try: import testcases except ImportError: logging.warn("Cannot find 'testcases' base package.") return None from pycopia import UI from pycopia.QA import core ui = UI.get_userinterface(themename="ANSITheme") ui.printf("Select any number of runnable objects. %n" "You can select %wmodules%N, %gUseCase%N objects, or single %yTest%N object.") # callback for testdir walker def filternames(flist, dirname, names): for name in names: if name.endswith(".py") and not name.startswith("_"): flist.append(os.path.join(dirname, name[:-3])) modnames = [] runnables = [] for testbase in testcases.__path__: mnlist = [] os.path.walk(testbase, filternames, mnlist) testhome_index = len(os.path.dirname(testbase)) + 1 modnames.extend(map(lambda n: n[testhome_index:].replace("/", "."), mnlist)) modnames.sort() for modname in modnames: try: mod = module.get_module(modname) except module.ModuleImportError: ui.warning(" Warning: could not import '{}'".format(modname)) continue if getattr(mod, "run", None) is not None: runnables.append(FormatWrapper(ui, modname, None, "%w%U%N")) for attrname in dir(mod): obj = getattr(mod, attrname) if type(obj) is type: if issubclass(obj, core.UseCase): runnables.append(FormatWrapper(ui, modname, obj.__name__, "%U.%g%O%N")) if issubclass(obj, core.Test): runnables.append(FormatWrapper(ui, modname, obj.__name__, "%U.%y%O%N")) return [o.fullname for o in ui.choose_multiple(runnables, prompt="Select tests")]
else: return self.modname def __str__(self): self._ui.register_format_expansion("O", self._str_name) self._ui.register_format_expansion("U", self._str_module) try: return self._ui.format(self._format) finally: self._ui.unregister_format_expansion("O") self._ui.unregister_format_expansion("U") def _str_name(self, c): return str(self.name) def _str_module(self, c): return str(self.modname) def __len__(self): return len(self.fullname) def __eq__(self, other): return self.modname == other.modname if __name__ == '__main__': from pycopia import UI ui = UI.get_userinterface(themename="ANSITheme") tests = choose_tests(ui) print(tests)
def configurator_cli(argv): """configurator_cli [-s <script>] [-g] <device> Interact with a DUT configurator. If no device is specified use the testbed DUT. Options: -g Use paged output (like 'more') -s <script> Run a CLI script from the given file instead of entering interactive mode. """ import os from pycopia.QA import configurator from pycopia import getopt from pycopia.storage import Storage paged = False script = None try: optlist, longopts, args = getopt.getopt(argv[1:], "s:?g") except GetoptError: print configurator_cli.__doc__ return for opt, val in optlist: if opt == "-?": print configurator_cli.__doc__ return elif opt == "-g": paged = True elif opt == "-s": script = val if not args: print configurator_cli.__doc__ return if paged: from pycopia import tty io = tty.PagedIO() else: io = IO.ConsoleIO() # do runtime setup cf = Storage.get_config(initdict=longopts) cf.reportfile = "configurator_cli" cf.logbasename = "configurator_cli.log" cf.arguments = argv dev = cf.devices[args[0]] ctor = configurator.get_configurator(dev, logfile=cf.logfile) # construct the CLI theme = ConfiguratorTheme("Configurator> ") ui = UI.UserInterface(io, cf, theme) cmd = CLI.get_generic_cmd(ctor, ui, ConfiguratorShellCLI) cmd.device = dev # stash actual device for future reference parser = CLI.CommandParser( cmd, historyfile=os.path.expandvars("$HOME/.hist_configurator")) if script: try: parser.parse(script) except KeyboardInterrupt: pass else: parser.interact() try: ctor.exit() except: pass