Sunday, July 22, 2012

Multiple Instances of a Remote Test Library in Robot Framework

One big shortcoming with the remote library API is that is has no mechanism for distinguishing between different instances of Robot Framework running either locally or remotely (i.e. it is a session-less protocol). If the library has any kind of state information, then two callers cannot reliably share the same instance of the library. This is clearly a problem when two tests are executing concurrently that both use the same library.

I have devised a simple solution that applies to execution by Jenkins if there is only one instance of Robot Framework running per executor. Jenkins defines many environmental variables that can be useful, including EXECUTOR_NUMBER, which is number of the executor running the current job. We can use this as an offset to a base port to be assured that each job will have its own instance of the remote library. For example, using a base port of 4000, the Robot Framework instance in executor #3 would use port 4003. The library must be parameterized so that the port can be chosen on startup. Here is some code showing how to start a library on the correct port prior to running Robot Framework in a Windows environment.
 set MY_REMOTE_LIBRARY_PORT=4000  
 if defined EXECUTOR_NUMBER set /a MY_REMOTE_LIBRARY_PORT=%MY_REMOTE_LIBRARY_PORT% + %EXECUTOR_NUMBER%  
 start java -jar my-remote-library.jar %MY_REMOTE_LIBRARY_PORT%  
When the library is imported, the appropriate port number must be used. You could set the variable as a command line argument to or use a variables file as shown below.
 import os  
   
 def get_variables():  
   port_offset = 0 if not 'EXECUTOR_NUMBER' in os.environ else int(os.environ['EXECUTOR_NUMBER'])  
   return {'MY REMOTE LIBRARY PORT': str(4000 + port_offset)}  
Note that if running outside of Jenkins, the base port is used.
The resource file would look something like this:
*** Settings ***
Variables         remote_library_port.py
Library           Remote    http://127.0.0.1:${MY REMOTE LIBRARY PORT}/
If you run Robot Framework instances in parallel in the same executor, then some other mechanism for assigning port numbers would be required. I cannot think of a simple, robust way to do this and would love to hear if you do.

No comments:

Post a Comment