def _register_functions(self): RobotRemoteServer._register_functions(self) if self.register_keywords: for lib in self._libraries.values(): self._register_library_keywords(lib) if self.introspection: self.register_introspection_functions()
def main(): # get configured logger logger = logging.getLogger("MAIN") # define arguments parser = ArgumentParser( prog="rxconnector", description="Remote ranorex library for robot framework") parser.add_argument("-i", "--ip", required=False, dest="ip", default="0.0.0.0") parser.add_argument("-p", "--port", required=False, type=int, dest="port", default=11000) # parse arguments args = parser.parse_args() # run server try: server = RobotRemoteServer(RanorexLibrary(), args.ip, args.port) except KeyboardInterrupt, e: logger.info("INFO: Keyboard Iterrupt: stopping server") server.stop_remote_server()
def __init__( self, libraries, host='127.0.0.1', port=8270, port_file=None, allow_stop=True, allow_import=None, register_keywords=True, introspection=True, ): """Takes a sequence of Test Library names to import, RobotRemoteServer's additional __init__ options and these optional extra args: :param allow_import: Sequence of Test Library names allowed for keyword `Import Remote Library`. :param register_keywords: Register imported Test Library Keywords directly as remote methods besides Dynamic Robot API methods? :param introspection: Call SimpleXMLRPCServer.register_introspection_functions()? """ TestRobot.__init__(self, name='Remote', BuiltIn=False) TestLibrary.__init__(self) self.register_keywords = bool(register_keywords) self.introspection = bool(introspection) for lib in libraries: self.Import(lib) self.allow_import = list(allow_import or []) # Initialize the RobotRemoteServer base # with a .library.RemoteLibrary proxy # (RobotRemoteServer only accepts a single library instance) RobotRemoteServer.__init__( self, RemoteLibrary(robot=self), host, port, port_file, allow_stop)
def __init__( self, libraries, host='127.0.0.1', port=8270, port_file=None, allow_stop=True, allow_import=None, register_keywords=True, introspection=True, ): """Takes a sequence of Test Library names to import, RobotRemoteServer's additional __init__ options and these optional extra args: :param allow_import: Sequence of Test Library names allowed for keyword `Import Remote Library`. :param register_keywords: Register imported Test Library Keywords directly as remote methods besides Dynamic Robot API methods? :param introspection: Call SimpleXMLRPCServer.register_introspection_functions()? """ TestRobot.__init__(self, name='Remote', BuiltIn=False) TestLibrary.__init__(self) self.register_keywords = bool(register_keywords) self.introspection = bool(introspection) for lib in libraries: self.Import(lib) self.allow_import = list(allow_import or []) # Initialize the RobotRemoteServer base # with a .library.RemoteLibrary proxy # (RobotRemoteServer only accepts a single library instance) RobotRemoteServer.__init__(self, RemoteLibrary(robot=self), host, port, port_file, allow_stop)
def __init__(self, port=5637, allow_stop=True): from socket import gethostname RobotRemoteServer.__init__(self, library=SikuliServer(), host=gethostname(), port=port, allow_stop=allow_stop)
def main(): lib = Espresso() # run server indefinitely try: server = RobotRemoteServer(lib, '0.0.0.0', 2347) except KeyboardInterrupt, e: log("INFO: Keyboard Iterrupt: stopping server") server.stop_remote_server()
def _handle_return_value(self, ret): from .sikuli_class import (ServerSikuliClass, UnimplementedSikuliClass) if isinstance(ret, ServerSikuliClass): return ret._marshallable() else: return RobotRemoteServer._handle_return_value(self, ret)
def main(argv): port = 8270 host = "0.0.0.0" allow_remote_stop = False try: opts, args = getopt.getopt(argv, "p:h:a", ["port=", "host=", "allowstop"]) except getopt.GetoptError: print( 'robotframework-remotestoragelibrary.py [-h <IP to listen>] [-p <port to listen>] [-a]' ) print( '-h / --host That IP address of the current server that the remote server will listen at. Defaults to all (0.0.0.0)' ) print( '-p / --port The Port the remote server will listen to. Default 8270' ) print( '-a / --allowstop Allow stopping the remote server with keyword "Stop Remote Server"' ) sys.exit(2) for opt, arg in opts: if opt in ("-h", "--host"): host = arg if opt in ("-p", "--port"): port = arg if opt in ("-a", "--allowstop"): allow_remote_stop = arg print('Allowing remote stop') RobotRemoteServer(library=StorageLibrary(), host=host, port=port, allow_remote_stop=allow_remote_stop)
def start_test_library(queue, backing_file, task_id, config, host, port): # importlib.invalidate_caches() testlib = importlib.import_module(backing_file) # importlib.reload(testlib) test = getattr(testlib, backing_file) server = RobotRemoteServer(test(config, task_id), host=host, serve=False, port=port) server_thread = threading.Thread(target=server.serve) server_thread.daemon = True server_thread.start() while True: try: item = queue.get() except KeyboardInterrupt: server._server.shutdown() break else: if item == TERMINATE: server._server.shutdown() break while server_thread.is_alive(): server_thread.join(0.1)
def start_library(library_name=""): try: RobotRemoteServer(ATTInterfaceUnit()) return None except Exception, e: log_data = "start %s library fail!\n message:%s" % (library_name, e) log.user_err(log_data) raise RuntimeError(log_data)
def main(): # get configured logger logger = logging.getLogger("MAIN") # define arguments parser = ArgumentParser(prog="rxconnector", description="Remote ranorex library for robot framework") parser.add_argument("-i","--ip", required=False, dest="ip", default="0.0.0.0") parser.add_argument("-p", "--port", required=False, type=int, dest="port", default=11000) # parse arguments args = parser.parse_args() # run server try: server = RobotRemoteServer(RanorexLibrary(), args.ip, args.port) except KeyboardInterrupt, e: logger.info("INFO: Keyboard Iterrupt: stopping server") server.stop_remote_server()
def import_shared_library(self, name): if name in self._remote_libraries: return self._remote_libraries[name][0] imported = TestLibrary(name) server = RobotRemoteServer(imported.get_instance(), port=0, serve=False, allow_stop=True) server_thread = threading.Thread(target=server.serve) server_thread.start() time.sleep(1) port = server.server_port self._remote_libraries[name] = (port, server, server_thread) return port
def main(params): try: # ----------------------------------------------------------------------------- # Start server # ----------------------------------------------------------------------------- api = Api(params) RobotRemoteServer(api, host=str(params['ip']), port=int(params['port'])) except Exception as e: print(str(e))
def start(self): log.debug("TestSpyPlugin started") spy = SystemTestSpy() # spies on NVDA server = self._server = RobotRemoteServer( NvdaSpyLib(spy), # provides library behaviour port=8270, # default:8270 is `registered by IANA` for remote server usage. Two ASCII values, RF. serve=False # we want to start this serving on another thread so as not to block. ) log.debug("Server address: {}".format(server.server_address)) server_thread = threading.Thread(target=server.serve) server_thread.start()
def main(params): try: # ---------------------------------------------------------------------- # Prepare enviroment # ---------------------------------------------------------------------- api = Api(params) # ---------------------------------------------------------------------- # Start server # ---------------------------------------------------------------------- RobotRemoteServer(api, host=params["ip"], port=params["port"]) except Exception as e: print(str(e))
def _start(self): log.debug("SystemTestSpyServer started") spyLibrary = NVDASpyLib() # spies on NVDA RobotRemoteServer = _importRobotRemoteServer() server = self._server = RobotRemoteServer( spyLibrary, # provides library behaviour port=8270, # default:8270 is `registered by IANA` for remote server usage. Two ASCII values, RF. serve=False # we want to start this serving on another thread so as not to block. ) log.debug("Server address: {}".format(server.server_address)) server_thread = threading.Thread(target=server.serve, name="RF Test Spy Thread") server_thread.start()
def main(): """ Main entry point for vmconnector""" # get configured logger logger = logging.getLogger("MAIN") # define arguments parser = ArgumentParser(prog="vmconnector", description="Robot Remote Server implementing VMware commands") # server configuration parser.add_argument("-i","--ip", required=False, dest="ip", default="0.0.0.0") parser.add_argument("-p", "--port", required=False, type=int, dest="port", default=8000) # password for VMware server os.environ["vmpass"] = "" if "vmpass" not in os.environ else os.environ["vmpass"] parser.add_argument("--vmpass", required=False, dest="vmpass", default=os.environ["vmpass"]) # vmware config file parser.add_argument("-c", "--config", required=True, dest="conf_path") # parse arguments args = parser.parse_args() if args.vmpass == "" : logger.error("VMware password not in environment variables") logger.error("Use vmconnector --vmpass PASSWORD") sys.exit(1) # save password into config dictionary! conf = parse_conf_to_dict(args.conf_path) conf["vm_server"]["vmpass"] = args.vmpass # run server try: server = RobotRemoteServer(vmlib.Library(conf), args.ip, args.port) except KeyboardInterrupt, e: log("INFO: Keyboard Iterrupt: stopping server") server.stop_remote_server()
break else: time.sleep(1) if status == 'disconnected': raise RuntimeError('wireless connect fail') if self.pingWait() == False: raise RuntimeError('wireless connect fail') def reStartWirelessService(self): cmdline = 'net stop WZCSVC' subprocess.check_output(cmdline,shell=True) cmdline = 'net start WZCSVC' subprocess.check_output(cmdline,shell=True) def wirelessConnect(self,ssid,key,security,encriType,authType,wpa_key_mode='asc'): self.WriteXMLProfile(ssid,key,security,encriType,authType,wpa_key_mode) cmdline = 'wcm.exe sp '+ self.guid +' '+self.XMLProfileFile subprocess.check_output(cmdline,shell=True) self.reStartWirelessService() self.waitWirelessConnect() def wirelessDisconnect(self,ssid): cmdline = 'wcm.exe dp '+ self.guid +' '+ ssid subprocess.call(cmdline,shell=True) if __name__ == '__main__': from robotremoteserver import RobotRemoteServer RobotRemoteServer(remoteWlconLib(sys.argv[3]), *sys.argv[1:])
def _arguments_from_kw(self, keyword): if isinstance(keyword, Keyword): return list(keyword.arguments) return RobotRemoteServer._arguments_from_kw(self, keyword)
def setUp(self): self.server = RobotRemoteServer(Library(), port=0, serve=False)
Get a value from previously reserved value set. """ key = key.lower() if self._remotelib: while True: value = self._remotelib.run_keyword('get_value_from_set', [key, self._my_id], {}) if value: return value time.sleep(0.1) logger.debug('waiting for a value') else: return _PabotLib.get_value_from_set(self, key, self._my_id) def release_value_set(self): """ Release a reserved value set so that other executions can use it also. """ if self._remotelib: self._remotelib.run_keyword('release_value_set', [self._my_id], {}) else: _PabotLib.release_value_set(self, self._my_id) if __name__ == '__main__': import sys RobotRemoteServer(_PabotLib(sys.argv[1]), host=sys.argv[2], port=sys.argv[3], allow_stop=True)
class TestServeAndStop(unittest.TestCase): def setUp(self): self.server = RobotRemoteServer(Library(), port=0, serve=False) def test_serve(self): self.assertEqual(self.server.server_port, 0) with self._server_thread(): uri = self._wait_until_started() try: self._run_remote_keyword(uri) finally: self.server.stop() self._wait_until_stopped(uri) self.assertEqual(test_remote_server(uri, log=False), False) def test_activate(self): port = self.server.activate() self.assertNotEqual(port, 0) self.assertEqual(port, self.server.server_port) with self._server_thread(): self.assertEqual(port, self.server.server_port) self.server.stop() @contextmanager def _server_thread(self): thread = threading.Thread(target=self.server.serve, kwargs={'log': False}) thread.start() try: yield finally: thread.join() def _wait_until_started(self, timeout=5): max_time = time.time() + timeout while time.time() < max_time: if self.server.server_port != 0: return 'http://%s:%s' % self.server.server_address time.sleep(0.01) raise AssertionError('Server did not start in %s seconds.' % timeout) def _run_remote_keyword(self, uri): origout = sys.stdout sys.stdout = StringIO() try: self.assertEqual(Remote(uri).run_keyword('kw', (), None), 42) self.assertEqual(sys.stdout.getvalue(), 'The message!\n') finally: sys.stdout.close() sys.stdout = origout def _wait_until_stopped(self, uri, timeout=5): max_time = time.time() + timeout while time.time() < max_time: if not test_remote_server(uri, log=False): return time.sleep(0.01) self.server.stop() raise AssertionError('Server did not stop in %s seconds.' % timeout) def test_stop_remote_server(self): with self._server_thread(): uri = self._wait_until_started() self.assertEqual(test_remote_server(uri, log=False), True) self.assertEqual(stop_remote_server(uri, log=False), True) self._wait_until_stopped(uri) self.assertEqual(stop_remote_server(uri, log=False), True)
raise AssertionError(message) def logging(self, message, level='INFO'): """This keywords logs given `message` with given `level` Example: | Logging | Hello, world! | | | Logging | Warning!!! | WARN | """ print '*%s* %s' % (level, message) def returning(self, value): """This keyword returns the given `value`.""" return value def _private_method(self): """This is not a keyword. Nor is the next one.""" pass def __private_method(self): pass attribute = 'Not a keyword' if __name__ == '__main__': import sys from robotremoteserver import RobotRemoteServer RobotRemoteServer(BasicCommunication(), '127.0.0.1', *sys.argv[1:])
(rc, err, errorstring) = UefiVar.SetUefiVar(name, guid, contents, attrs) return rc def remote_ack(self): return True def remote_get_version(self): return RobotRemoteVersion def remote_warm_reboot(self): os.system("shutdown -r -t 1") if __name__ == '__main__': from robotremoteserver import RobotRemoteServer print("Version %s - %s" % (str(RobotRemoteVersion), RobotRemoteChangeDate)) #setup main console as logger logger = logging.getLogger('') logger.setLevel(logging.DEBUG) formatter = logging.Formatter("%(levelname)s - %(message)s") console = logging.StreamHandler() console.setLevel(logging.CRITICAL) console.setFormatter(formatter) logger.addHandler(console) RobotRemoteServer(UefiRemoteTesting(), host='0.0.0.0', port=8270) logging.shutdown() sys.exit(retcode)
print(message, file=stream) def multiple_messages_with_different_levels(self): print('Info message') print('*DEBUG* Debug message') print('*INFO* Second info') print('this time with two lines') print('*INFO* Third info') print('*TRACE* This is ignored') print('*WARN* Warning') def logging_and_failing(self): print('*INFO* This keyword will fail!') print('*WARN* Run for your lives!!') raise AssertionError('Too slow') def logging_and_returning(self, logged, returned): print(logged) return returned def logging_both_to_stdout_and_stderr(self, *messages): for index, msg in enumerate(messages): stream = sys.stdout if index % 2 == 0 else sys.stderr stream.write(msg) if __name__ == '__main__': from robotremoteserver import RobotRemoteServer RobotRemoteServer(Logging(), '127.0.0.1', *sys.argv[1:])
return eval(value) class MyObject(object): def __init__(self, name='<MyObject>'): self.name = name def __str__(self): return self.name class MyMapping(Mapping): def __init__(self, data=None, **extra): self.data = dict(data or {}, **extra) def __getitem__(self, item): return self.data[item] def __len__(self): return len(self.data) def __iter__(self): return iter(self.data) if __name__ == '__main__': import sys from robotremoteserver import RobotRemoteServer RobotRemoteServer(Returning(), '127.0.0.1', *sys.argv[1:])
from robotremoteserver import RobotRemoteServer from liberia_remota import SistemaBancario server = RobotRemoteServer(SistemaBancario(), serve=False) server.serve()
#!/usr/bin/env python import os import sys from Selenium2Library import Selenium2Library class SeleniumLib(Selenium2Library): def __init__(self): Selenium2Library.__init__(self) """Also this doc should be in shown in library doc.""" if __name__ == '__main__': from robotremoteserver import RobotRemoteServer RobotRemoteServer(SeleniumLib(), *sys.argv[1:])
import sys import os from robotremoteserver import RobotRemoteServer from CryptoLibrary import CryptoLibrary # test variable_decryption=True key_path=${CURDIR}/private_key.json if __name__ == '__main__': dir_path = os.path.dirname(os.path.realpath(__file__)) PORT = os.getenv('PORT', 8270) RobotRemoteServer(CryptoLibrary(password="******",variable_decryption=True,key_path=dir_path), host="0.0.0.0", port=PORT, *sys.argv[1:])
def main(): import sys from robotremoteserver import RobotRemoteServer print("Starting Robot Framework Ftp Library as a remote server ...") RobotRemoteServer(library=FtpLibrary(), host=sys.argv[1], port=sys.argv[2])
#!/usr/bin/env python import os import sys class ExampleRemoteLibrary: """Example library to be used with Robot Framework's remote server. This documentation is visible in docs generated by _libdoc.py_ starting from Robot Framework 2.6.2. """ def __init__(self): """Also this doc should be in shown in library doc.""" def count_items_in_directory(self, path): """Returns the number of items in the directory specified by `path`.""" return len([i for i in os.listdir(path) if not i.startswith('.')]) def strings_should_be_equal(self, str1, str2): print "Comparing '%s' to '%s'" % (str1, str2) if str1 != str2: raise AssertionError("Given strings are not equal") if __name__ == '__main__': from robotremoteserver import RobotRemoteServer RobotRemoteServer(ExampleRemoteLibrary(), *sys.argv[1:])
import sys import os from robotremoteserver import RobotRemoteServer from keywords import RemoteDemoLibrary if __name__ == '__main__': PORT = os.getenv('PORT', 8270) RobotRemoteServer(RemoteDemoLibrary(), host="0.0.0.0", port=PORT, *sys.argv[1:])
def kwargs(self, **kwargs): return self._format_args(**kwargs) def args_and_kwargs(self, arg1, arg2='default', **kwargs): return self._format_args(arg1, arg2, **kwargs) def varargs_and_kwargs(self, *varargs, **kwargs): return self._format_args(*varargs, **kwargs) def args_varargs_and_kwargs(self, arg1='default1', arg2='default2', *varargs, **kwargs): return self._format_args(arg1, arg2, *varargs, **kwargs) def _format_args(self, *args, **kwargs): args += tuple('%s:%s' % (k, self._format_arg(v)) for k, v in sorted(kwargs.items())) return ', '.join(self._format_arg(a) for a in args) def _format_arg(self, arg): if isinstance(arg, basestring): return arg return '%s (%s)' % (arg, type(arg).__name__) if __name__ == '__main__': import sys from robotremoteserver import RobotRemoteServer RobotRemoteServer(Arguments(), '127.0.0.1', *sys.argv[1:])
ret = auto_do_remote(cls) if not ret: ret = None else: ret = cls.get_nic_name_or_mac(name_or_mac) return ret def start_library(host="172.0.0.1", port=REMOTE_PORT, library_name=""): try: log.start_remote_process_log(library_name) except ImportError, e: raise RuntimeError(u"创建log模块失败,失败信息:%" % e) try: RobotRemoteServer(NetConfig(), host, port) return None except Exception, e: log_data = "start %s library fail!\n message:%s" % (library_name, e) log.user_err(log_data) raise RuntimeError(log_data) def test(): cls1 = NetConfig() cls1.init_nic_card("1", u"办公网") cls1.get_nic_ipv4_address() cls1.init_nic_card("1", u"本地连接 2", "http://10.10.10.6:58007") cls1.get_nic_ipv4_address() '''
except KeyError: raise AttributeError(name) def passing(arg=None): assert not arg or '=' not in arg def failing(message): raise AssertionError(message) def logging(message, level='INFO'): print('*%s* %s' % (level, message)) def returning(): return 'Hello, world!' def kwargs(expected, **kws): actual = ', '.join('%s: %s' % (k, kws[k]) for k in sorted(kws)) assert actual == expected if __name__ == '__main__': import sys from robotremoteserver import RobotRemoteServer RobotRemoteServer(Hybrid(), '127.0.0.1', *sys.argv[1:])