Saturday, November 2, 2013

Get IP of Grid node when using Selenium2Library & Robot Framework

Sometimes it is useful to know which machine is executing a Selenium test when using Selenium Grid.

The following code was adapted from a post written in Java. I converted it into a keyword for Robot Framework and added code to grab the session ID from Selenium2Library.

 import urllib2, json  
 from robot.libraries.BuiltIn import BuiltIn  
 from robot.api import logger  
 from urlparse import urlparse  

 def get_node_hostname(hub_url):  
    '''Returns the hostname/IP of the node executing the session belonging to the active browser.'''  
     
    s2l = BuiltIn().get_library_instance('Selenium2Library')  
    session_id = s2l._current_browser().session_id  
    parse_result = urlparse(hub_url)  
    host = parse_result.hostname  
    port = parse_result.port  
    query_url = 'http://%s:%s/grid/api/testsession?session=%s' % (host, port, session_id)  
    req = urllib2.Request(url=query_url)  
    resp = urllib2.urlopen(req).read()  
    json_blob = json.loads(resp)  
    if 'proxyId' in json_blob:  
        proxy_id = json_blob['proxyId']  
        print '*INFO* proxyId is %s' % proxy_id  
        parse_result = urlparse(proxy_id)  
        return parse_result.hostname  
    else:  
        raise RuntimeError('Failed to get hostname. Is Selenium running locally? hub response: %s' % resp)

No comments:

Post a Comment