def __init__(self, name): """ Import a library so that the library instance is shared between executions. [https://pabot.org/PabotLib.html?ref=log#import-shared-library|Open online docs.] """ # FIXME: RELATIVE IMPORTS WITH FILE NAME self._remote = None if BuiltIn().get_variable_value("${%s}" % PABOT_QUEUE_INDEX) is None: logger.debug( "Not currently running pabot. Importing library for this process." ) self._lib = RemoteLibraryFactory(TestLibrary(name).get_instance()) return uri = BuiltIn().get_variable_value("${PABOTLIBURI}") logger.debug("PabotLib URI %r" % uri) remotelib = Remote(uri) if uri else None if remotelib: try: port = remotelib.run_keyword("import_shared_library", [name], {}) except RuntimeError: logger.error("No connection - is pabot called with --pabotlib option?") raise self._remote = Remote("http://127.0.0.1:%s" % port) logger.debug( "Lib imported with name %s from http://127.0.0.1:%s" % (name, port) ) else: logger.error("No connection - is pabot called with --pabotlib option?") raise AssertionError("No connection to pabotlib")
def remote_run_keyword(self, uri, name, *args): '''可以使用这个关键字在远程机上运行远程机的关键字。 uri=http://192.168.7.108:8270 远程机的IP和端口。 name=keyword 在远程机上运行的关键字。 *args=args 关键字参数,可以是多个,用括号括起来。 你可以在suit的添加全局变量,定义uri。 ''' client = Remote(uri) client.run_keyword(name=name, args=args, kwargs=False)
def remote_run_keyword(self,uri,name,*args): '''可以使用这个关键字在远程机上运行远程机的关键字。 uri=http://192.168.7.108:8270 远程机的IP和端口。 name=keyword 在远程机上运行的关键字。 *args=args 关键字参数,可以是多个,用括号括起来。 你可以在suit的添加全局变量,定义uri。 ''' client=Remote(uri) client.run_keyword(name=name,args=args,kwargs=False)
def init_wireshark_network_card(self, alias, name_or_mac, remote_url=False): """ 功能描述:初始化网卡,为网卡配置别名; 参数: alias:别名\n name_or_mac:网卡名称或者是MAC地址\n remote_url:是否要进行远程控制。(默认不进行远程)。\n remote_url格式为:http://remote_IP.可以用以下的几种方式进行初始化。注意别名请设置为 不同的别名,切换的时候用别名进行切换。 返回值:无 Example: | Init WireShark Network Card | One | 本地连接1 | | Init WireShark Network Card | two | 本地连接1 | http://10.10.10.84 | | Init WireShark Network Card | 3 | 44-37-E6-99-7C-B9 | | Init WireShark Network Card | 4 | 44:37:E6:99:7C:B9 | """ # 输入的name_or_mac做转换,除去格式的差异 name_or_mac = modified_name_or_mac(name_or_mac) # 对用户输入的remote_url做处理转换,添加http://头等 remote_url = modified_remote_url(remote_url) if (is_remote(remote_url)): # already init? ret_alias = self._is_init(name_or_mac, remote_url, alias) if (ret_alias): reallib = self._cache.switch(ret_alias) else: reallib = Remote(remote_url) reallib._client.set_timeout( REMOTE_TIMEOUT) # add connection remote timeout zsj 2013-3-28 network_name, network_mac = auto_do_remote(reallib) else: # already init? ret_alias = self._is_init(name_or_mac, remote_url, alias) if (ret_alias): reallib = self._cache.switch(ret_alias) else: reallib = ATTWireShark(name_or_mac) network_name = reallib.get_network_name() network_mac = reallib.get_network_mac() tag = self._cache.register(reallib, alias) self._register_alias(alias, network_name, network_mac, remote_url) return network_name, network_mac
def _check_java_application_is_available_on_port(self, port): remote_url = "http://127.0.0.1:{0}".format(port) try: remote_java_app = Remote(remote_url) # Drop timeout on connection attempt to 3 seconds socket.setdefaulttimeout(3) # Call method on server to check if there is actually a server there. Only try onec though remote_java_app.get_keyword_names(attempts=1) # Set timeout back to default socket.setdefaulttimeout(None) except: return False return True
def _run_keyword_in_java_application(self, name, args, **kwargs): remote_url = "http://127.0.0.1:{0}".format(self._port) remote_java_app = Remote(remote_url) try: # Convert all the arguments to strings string_arguments = [] for argument in args: string_arguments.append(str(argument)) # The interface of the Remote library changes in robot framework 2.8.3 to take an additional dictionary for keyword arguments if robot.version.get_version() >= '2.8.3': return_value = remote_java_app.run_keyword(name, string_arguments, kwargs) else: return_value = remote_java_app.run_keyword(name, string_arguments) except Exception as inst: # Take a screenshot if, we need to if self._take_screenshot_on_failure: output_directory = BuiltIn().replace_variables('${OUTPUTDIR}') screenshot_file_name = 'screenshot_java_0000.png' index = 0 while os.path.exists(os.path.join(output_directory, screenshot_file_name)): index += 1 screenshot_file_name = 'screenshot_java_{0:04d}.png'.format(index) # Use the remote library directly to avoid infinite loops # The interface of the Remote library changes in robot framework 2.8.3 to take an additional dictionary for keyword arguments if robot.version.get_version() >= '2.8.3': remote_java_app.run_keyword("takeScreenshot", [os.path.join(output_directory, screenshot_file_name)], {}) else: remote_java_app.run_keyword("takeScreenshot", [os.path.join(output_directory, screenshot_file_name)]) # Log link to screenshot in ancjhor to make the screenshot clickable for a bigger version logger.info('<a href="{0}"><img src="{0}" width="600px" /></a>'.format( screenshot_file_name.replace("\\", "/")), html=True) # Raise exception back to robot framework raise return return_value
class SharedLibrary(object): ROBOT_LIBRARY_SCOPE = 'GLOBAL' def __init__(self, name): """ Import a library so that the library instance is shared between executions. [https://pabot.org/PabotLib.html?ref=log#import-shared-library|Open online docs.] """ # FIXME: RELATIVE IMPORTS WITH FILE NAME self._remote = None if BuiltIn().get_variable_value('${%s}' % PABOT_QUEUE_INDEX) is None: logger.debug( "Not currently running pabot. Importing library for this process." ) self._lib = RemoteLibraryFactory(TestLibrary(name).get_instance()) return uri = BuiltIn().get_variable_value('${PABOTLIBURI}') logger.debug('PabotLib URI %r' % uri) remotelib = Remote(uri) if uri else None if remotelib: try: port = remotelib.run_keyword("import_shared_library", [name], {}) except RuntimeError: logger.error( 'No connection - is pabot called with --pabotlib option?') raise self._remote = Remote("http://127.0.0.1:%s" % port) logger.debug("Lib imported with name %s from http://127.0.0.1:%s" % (name, port)) else: logger.error( 'No connection - is pabot called with --pabotlib option?') raise AssertionError('No connection to pabotlib') def get_keyword_names(self): if self._remote: return self._remote.get_keyword_names() return self._lib.get_keyword_names() def run_keyword(self, name, args, kwargs): if self._remote: return self._remote.run_keyword(name, args, kwargs) result = self._lib.run_keyword(name, args, kwargs) if result['status'] == 'FAIL': raise AssertionError(result['error']) return result.get('return')
def _try_execute_and_wait(cmd, outs_dir, item_name, verbose, pool_id, caller_id): try: with open(os.path.join(outs_dir, cmd[0] + '_stdout.txt'), 'w') as stdout: with open(os.path.join(outs_dir, cmd[0] + '_stderr.txt'), 'w') as stderr: process, (rc, elapsed) = _run(cmd, stderr, stdout, item_name, verbose, pool_id) except: print(sys.exc_info()[0]) # Thread-safe list append _ALL_ELAPSED.append(elapsed) if rc != 0: _write_with_id( process, pool_id, _execution_failed_message(item_name, stdout, stderr, rc, verbose), Color.RED) if _PABOTLIBPROCESS or _PABOTLIBURI != '127.0.0.1:8270': Remote(_PABOTLIBURI).run_keyword('release_locks', [caller_id], {}) else: _write_with_id( process, pool_id, _execution_passed_message(item_name, stdout, stderr, elapsed, verbose), Color.GREEN)
def execute_and_wait_with(args): global CTRL_C_PRESSED if CTRL_C_PRESSED: # Keyboard interrupt has happened! return time.sleep(0) datasources, outs_dir, options, suite_name, command, verbose, (argfile_index, argfile) = args datasources = [d.encode('utf-8') if PY2 and is_unicode(d) else d for d in datasources] outs_dir = os.path.join(outs_dir, argfile_index, suite_name) pool_id = _make_id() caller_id = uuid.uuid4().hex cmd = command + _options_for_custom_executor(options, outs_dir, suite_name, argfile, caller_id) + datasources cmd = [c if not any(bad in c for bad in _BOURNELIKE_SHELL_BAD_CHARS_WITHOUT_DQUOTE) else '"%s"' % c for c in cmd] os.makedirs(outs_dir) try: with open(os.path.join(outs_dir, 'stdout.txt'), 'w') as stdout: with open(os.path.join(outs_dir, 'stderr.txt'), 'w') as stderr: process, (rc, elapsed) = _run(cmd, stderr, stdout, suite_name, verbose, pool_id) except: print(sys.exc_info()[0]) if rc != 0: _write_with_id(process, pool_id, _execution_failed_message(suite_name, stdout, stderr, rc, verbose), Color.RED) if _PABOTLIBPROCESS or _PABOTLIBURI != '127.0.0.1:8270': Remote(_PABOTLIBURI).run_keyword('release_locks', [caller_id], {}) else: _write_with_id(process, pool_id, _execution_passed_message(suite_name, stdout, stderr, elapsed, verbose), Color.GREEN)
def init_ftp_client(self, alias, port, remote_url=False): """ 功能描述:初始化执行ftp client; 参数: alias:别名; port:服务器所打开的端口号; remote_url:是否要进行远程控制; 格式为:http://remote_IP.可以用以下的几种方式进行初始化。 注意别名请设置为不同的别名,切换的时候用别名进行切换。 Example: | Init Ftp Client | Local | 21 | | Init Ftp Client | remote | 21 | http://10.10.10.85 | """ # 对用户输入的remote_url做处理转换,添加http://头等 remote_url = modified_remote_url(remote_url) if (is_remote(remote_url)): # already init? ret_alias = self._is_init(alias, port, remote_url) if (ret_alias): reallib = self._cache.switch(ret_alias) else: reallib = Remote(remote_url) reallib._client.set_timeout( REMOTE_TIMEOUT) # add connection remote timeout zsj 2013-3-28 auto_do_remote(reallib) else: # already init? ret_alias = self._is_init(alias, port, remote_url) if (ret_alias): reallib = self._cache.switch(ret_alias) #清空之前建立的连接对象 #add by jias 20130810 #当相同的2个用例一起执行的时候,第二个用例初始化时,会直接去第一用的ftpclient对象, #这时,远端server已经重新启动,故清空之前的连接和标志 reallib.clear() else: reallib = ATTFtpClient(port) tag = self._cache.register(reallib, alias) self._register_alias(alias, port, remote_url) return tag
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 init_nic_card(self, alias, name_or_mac, remote_url=False): """ 功能描述:初始化网卡,为网卡配置别名; 注意:用MAC地址来初始化,禁用网卡之后,启用网卡会有问题。 需要在网卡禁用之后,再启用网卡的,请不要用MAC进行初始化,可以用网卡名称实现初始化。 参数: alias:别名; name_or_mac:网卡名称或者是MAC地址; remote_url:是否要进行远程控制(默认不进行远程),remote_url格式为:http://remote_IP; 可以用以下的几种方式进行初始化。请设置不同的别名,切换的时候用别名进行切换。 返回值:无 Example: | Init Nic Card | One | 本地连接1 | | Init Nic Card | two | 本地连接1 | http://10.10.10.84 | | Init Nic Card | 3 | 44-37-E6-99-7C-B9 | | Init Nic Card | 4 | 44:37:E6:99:7C:B9 | """ # 输入的name_or_mac做转换,除去格式的差异 name_or_mac = modified_name_or_mac(name_or_mac) # 对用户输入的remote_url做处理转换,添加http://头等 remote_url = modified_remote_url(remote_url) if (is_remote(remote_url)): # already init? ret_alias = self._is_init(name_or_mac, remote_url, alias) if (ret_alias): reallib = self._cache.switch(ret_alias) else: reallib = Remote(remote_url) reallib._client.set_timeout( REMOTE_TIMEOUT) # add connection remote timeout zsj 2013-3-28 name, mac_address = auto_do_remote(reallib) else: # already init? ret_alias = self._is_init(name_or_mac, remote_url, alias) if (ret_alias): reallib = self._cache.switch(ret_alias) else: reallib = ATTNetConfig(name_or_mac) name = reallib.name mac_address = reallib.mac_address tag = self._cache.register(reallib, alias) self._register_alias(alias, name, mac_address, remote_url) return name, mac_address
def _stop_remote_library(process): print 'Stopping PabotLib process' Remote(_PABOTLIBURI).run_keyword('stop_remote_server', [], {}) i = 50 while i > 0 and process.poll() is None: time.sleep(0.1) i -= 1 if i == 0: print 'Could not stop PabotLib Process in 5 seconds - calling terminate' process.terminate() else: print 'PabotLib process stopped'
def _stop_remote_library(process): _write('Stopping PabotLib process') Remote(_PABOTLIBURI).run_keyword('stop_remote_server', [], {}) i = 50 while i > 0 and process.poll() is None: time.sleep(0.1) i -= 1 if i == 0: _write('Could not stop PabotLib Process in 5 seconds ' \ '- calling terminate', Color.YELLOW) process.terminate() else: _write('PabotLib process stopped')
def init_telnet_connection(self, alias, host, remote_url=False): """ 功能描述:初始化telnet连接,将本端或远端的telnet使用别名代替,方便后面的切换; 参数: alias:用户自定义的telnet连接别名; host:将要打开的telnet连接CPE的IP地址; remote_url:配置远端地址,默认为False,即不启用远端; 返回值: 初始化telnet连接的个数; Example: | Init Telnet Connection | local | 192.168.1.1 | | Init Telnet Connection | remote | 192.168.1.1 | http://172.16.28.55 | """ # 对用户输入的remote_url做处理转换,添加http://头等 remote_url = modified_remote_url(remote_url) if (is_remote(remote_url)): # already init? ret_alias = self._is_init(alias, host, remote_url) if (ret_alias): reallib = self._cache.switch(ret_alias) else: reallib = Remote(remote_url) self.list_cls_remote.append( reallib) # lwb: 2013-04-20 把所有的ATTTelnet对象放在实例列表中 reallib._client.set_timeout( REMOTE_TIMEOUT) # add connection remote timeout zsj 2013-3-28 auto_do_remote(reallib) else: # already init? ret_alias = self._is_init(alias, host, remote_url) if (ret_alias): reallib = self._cache.switch(ret_alias) else: reallib = ATTTelnet(host) self.list_cls_local.append( reallib) # lwb: 2013-04-20 把本端的ATTTelnet对象放在本端实例列表中 tag = self._cache.register(reallib, alias) self._register_alias(alias, host, remote_url) return tag
def runkey(*args,**kwargs): rem=Remote(uri='http://172.17.21.111:8270') print('rem ',rem) keywork_name=rem.get_keyword_names() print(keywork_name) rem.run_keyword('http_serv',args=args,kwargs=kwargs) #time.sleep(60) #rem.run_keyword('stop_remote_server',args=args,kwargs=kwargs) rem.run_keyword('http_serv_stop',args=args,kwargs=kwargs)
class JavaRemoteClient(object): def __init__(self, url, keyword_class): self.keyword_class = keyword_class self._robot_remote = Remote(url) self._keyword_names = None self._keyword_arguments = {} self._keyword_documentation = {} def get_keyword_names(self): """Returns a list of available keywords.""" if self._keyword_names is None: self._keyword_names = self._robot_remote.get_keyword_names() if 'stop_remote_server' in self._keyword_names: self._keyword_names.remove('stop_remote_server') return self._keyword_names def run_keyword(self, name, args, kwargs): """Runs given keyword.""" result = self._robot_remote.run_keyword(name, args, kwargs) return self._wrap_if_dict(result) def _wrap_if_dict(self, value): return object_dict(value) if isinstance(value, dict) else value def get_keyword_arguments(self, name): """Returns a list of argument names for given keyword.""" if name not in self._keyword_arguments: self._keyword_arguments[name] = self._robot_remote.get_keyword_arguments(name) return self._keyword_arguments[name] def get_keyword_documentation(self, name): """Returns the documentation for given keyword.""" if name not in self._keyword_documentation: self._keyword_documentation[name] = self._robot_remote.get_keyword_documentation(name) return self._keyword_documentation[name]
def init_http_server(self, alias, port, remote_url=False): """ 功能描述:初始化HTTP服务器 参数: alias:别名; port:打开服务所用的端口号; remote_url:是否要进行远程控制; 格式为:http://remote_IP.可以用一下的几种方式进行初始化。 注意别名请设置为不同的别名,切换的时候用别名进行切换。 Example: | Init Http Server | Local | 8080 | | Init Http Server | remote | 8080 | http://10.10.10.85 | """ #检查PORT数据的合法性 ret,data = check_port(port) if ret == ATTCOMMONFUN_FAIL: raise RuntimeError(u"关键字执行失败,端口号为非法数据!") # 对用户输入的remote_url做处理转换,添加http://头等 remote_url = modified_remote_url(remote_url) if (is_remote(remote_url)): # already init? ret_alias = self._check_init_alias(alias, port, remote_url) if (ret_alias): reallib = self._switch_current_object(ret_alias) else: reallib = Remote(remote_url) reallib._client.set_timeout(REMOTE_TIMEOUT) # add connection remote timeout zsj 2013-3-28 auto_do_remote(reallib) else: # already init? ret_alias = self._check_init_alias(alias, port, remote_url) if (ret_alias): reallib = self._switch_current_object(ret_alias) else: try: #TODO #创建ATTTWHttpServer实例对象 reallib = ATTTWHttpServer(port) except Exception,e: raise RuntimeError(u"初始化ATTTWHttpServer对象失败")
def init_udp_server(self, alias, remote_url=False): """ 功能描述:初始化一个本地或远端的UDP Server; 参数: alias:UDP Server的别名,用于唯一标识某一个UDP Server; remote_url:如果要进行远程控制,传入远程控制的地址,格式为:http://remote_IP;否则使用默认值; 注意别名请设置为不同的别名,切换的时候用别名进行切换。 Example: | Init Udp Server | local | | | Init Udp Server | remote | http://10.10.10.85 | """ # 检测用户输入的remote_url是否有“http://”头,如果没有则自动添加 remote_url = modified_remote_url(remote_url) # 本地和远端采用不同的处理 if (is_remote(remote_url)): # 判断当前别名是否已经初始化了,如果初始化了,则切换之前注册的remote object,否则新注册一个Remote object ret_alias = self._is_init(alias, remote_url) if (ret_alias): reallib = self._cache.switch(ret_alias) else: reallib = Remote(remote_url) # 设置远端连接的超时 reallib._client.set_timeout(REMOTE_TIMEOUT) # 发送消息到远端执行 auto_do_remote(reallib) else: # 判断当前别名是否已经初始化了,如果初始化了,则切换之前注册的local object,否则新注册一个local object ret_alias = self._is_init(alias, remote_url) if (ret_alias): reallib = self._cache.switch(ret_alias) else: reallib = ATTUDPServer() # 注册object对象和别名 tag = self._cache.register(reallib, alias) # 注册别名和remote_url self._register_alias(alias, remote_url) return tag
def init_ftp_server(self, alias, port, remote_url=False): """ 功能描述:初始化执行ftp server; 参数: alias:别名; port:打开服务所用的端口号; remote_url:是否要进行远程控制; 格式为:http://remote_IP.可以用以下的几种方式进行初始化。 注意别名请设置为不同的别名,切换的时候用别名进行切换。 Example: | Init Ftp Server | Local | 21 | | Init Ftp Server | remote | 21 | http://10.10.10.85 | """ # 对用户输入的remote_url做处理转换,添加http://头等 remote_url = modified_remote_url(remote_url) if (is_remote(remote_url)): # already init? ret_alias = self._is_init(alias, port, remote_url) if (ret_alias): reallib = self._cache.switch(ret_alias) else: reallib = Remote(remote_url) reallib._client.set_timeout( REMOTE_TIMEOUT) # add connection remote timeout zsj 2013-3-28 auto_do_remote(reallib) else: # already init? ret_alias = self._is_init(alias, port, remote_url) if (ret_alias): reallib = self._cache.switch(ret_alias) else: reallib = ATTFtpServer(port) tag = self._cache.register(reallib, alias) self._register_alias(alias, port, remote_url) return tag
def _addMethodsToSpy(remoteLib: _Remote): """ Adds a method for each keywords on the remote library. @param remoteLib: the library to augment with methods. @rtype: SystemTestSpy.speechSpyGlobalPlugin.NVDASpyLib @return: The library augmented with methods for all keywords. """ # Add methods back onto the lib so they can be called directly rather than manually calling run_keyword def _makeKeywordCaller(lib, keyword): def runKeyword(*args, **kwargs): builtIn.log(f"{keyword}" f"{f' {args}' if args else ''}" f"{f' {kwargs}' if kwargs else ''}") return lib.run_keyword(keyword, args, kwargs) return runKeyword for name in remoteLib.get_keyword_names(): setattr(remoteLib, name, _makeKeywordCaller(remoteLib, name)) return remoteLib
def init_ping_site(self, alias, remote_url=False): """ 功能描述:初始化执行ping的主机 参数:alias:别名。remote_url:是否要进行远程控制。(默认不进行远程)。 格式为:http://remote_IP.可以用以下几种方式进行初始化。 注意请设置为不同的别名,切换时用别名进行切换。 返回值:无 Example: | Init Ping Site | One | #初始化本地Ping主机 | | Init Ping Site | two | http://10.10.10.84 | #初始化远程Ping主机 | """ # 对用户输入的remote_url做处理转换,添加http://头等 remote_url = modified_remote_url(remote_url) if (is_remote(remote_url)): # already init? ret_alias = self._is_init(alias, remote_url) if (ret_alias): reallib = self._cache.switch(ret_alias) else: reallib = Remote(remote_url) reallib._client.set_timeout( REMOTE_TIMEOUT) # add connection remote timeout zsj 2013-3-28 auto_do_remote(reallib) else: # already init? ret_alias = self._is_init(alias, remote_url) if (ret_alias): reallib = self._cache.switch(ret_alias) else: reallib = ATTPing() tag = self._cache.register(reallib, alias) self._register_alias(alias, remote_url) return tag
def _initialize_remote_libraries(self, alias, url): swinglibrary = Remote(url) logger.debug('remote swinglibrary instantiated') services = Remote(url + '/services') logger.debug('remote services instantiated') self.REMOTES[alias] = [swinglibrary, services]
def stop_local_Rserver(self): from robot.libraries.Remote import Remote local_server=Remote(uri="http://127.0.0.1:8270") local_server.run_keyword(name="stop_remote_server",args="",kwargs="") print("local server is stop")
def _connect_remote_library(self): remoteUrl = 'http://127.0.0.1:%s/' % str(self.port) remote = Remote(remoteUrl) self._test_get_keyword_names(remote) return remote
def _remotelib(self): if self.__remotelib is None: uri = BuiltIn().get_variable_value('${PABOTLIBURI}') logger.debug('PabotLib URI %r' % uri) self.__remotelib = Remote(uri) if uri else None return self.__remotelib
def __init__(self, url, keyword_class): self.keyword_class = keyword_class self._robot_remote = Remote(url) self._keyword_names = None self._keyword_arguments = {} self._keyword_documentation = {}
def __init__(self, uri, proxy=None): Remote.__init__(self, uri) self._client = ProxyableXmlRpcRemoteClient(uri, proxy)
def stop_local_Rserver(self): from robot.libraries.Remote import Remote local_server = Remote(uri="http://127.0.0.1:8270") local_server.run_keyword(name="stop_remote_server", args="", kwargs="") print("local server is stop")