code
stringlengths
1
1.49M
vector
listlengths
0
7.38k
snippet
listlengths
0
7.38k
#! /usr/bin/python import roslib; roslib.load_manifest('rfid_people_following') roslib.load_manifest('std_srvs') roslib.load_manifest('explore_hrl') roslib.load_manifest('move_base_msgs') roslib.load_manifest('actionlib') roslib.load_manifest('geometry_msgs') roslib.load_manifest('tf') roslib.load_manifest('hrl_rfid') import rospy import tf import tf.transformations as tft import actionlib from move_base_msgs.msg import MoveBaseAction, MoveBaseGoal import hrl_rfid.ros_M5e_client as rmc from rfid_people_following.srv import StringInt32_Int32 from rfid_people_following.srv import String_Int32 from rfid_people_following.srv import Int32_Int32 from rfid_people_following.srv import String_StringArr from std_srvs.srv import Empty from geometry_msgs.msg import PointStamped import actionlib import explore_hrl.msg from geometry_msgs.msg import PoseStamped from geometry_msgs.msg import Quaternion import numpy as np, math import time from threading import Thread import os # A more general form of this should be folded back into ros_M5e_client! # It also appears in new_servo_node (rfid_people_following) class rfid_poller( Thread ): def __init__( self, tagid ): Thread.__init__( self ) self.reader = rmc.ROS_M5e_Client('ears') self.listener = tf.TransformListener() self.listener.waitForTransform('/ear_antenna_left', '/map', rospy.Time(0), timeout = rospy.Duration(100) ) self.listener.waitForTransform('/ear_antenna_right', '/map', rospy.Time(0), timeout = rospy.Duration(100) ) self.should_run = True self.should_poll = False self.data = [] self.tagid = tagid self.start() def transform( self, antname ): ps = PointStamped() ps2 = PointStamped() ps2.point.x = 0.1 if antname == 'EleLeftEar': ps.header.frame_id = '/ear_antenna_left' ps.header.stamp = rospy.Time( 0 ) ps2.header.frame_id = '/ear_antenna_left' ps2.header.stamp = rospy.Time( 0 ) elif antname == 'EleRightEar': ps.header.frame_id = '/ear_antenna_right' ps.header.stamp = rospy.Time( 0 ) ps2.header.frame_id = '/ear_antenna_right' ps2.header.stamp = rospy.Time( 0 ) else: rospy.logout( 'Bad ear' ) return False, 0.0, 0.0, 0.0 try: ps_map = self.listener.transformPoint( '/map', ps ) x = ps_map.point.x y = ps_map.point.y #rospy.logout( 'Done 1' ) ps2_map = self.listener.transformPoint( '/map', ps2 ) x2 = ps2_map.point.x y2 = ps2_map.point.y #rospy.logout( 'Done 1' ) #rospy.logout( 'Transform Success ' + ps.header.frame_id ) return True, x, y, np.arctan2( y2 - y, x2 - x ) except: rospy.logout( 'Transform failed! ' + ps.header.frame_id ) return False, 0.0, 0.0, 0.0 def start_poller( self ): # Start appending into self.data #self.reader.track_mode( self.tagid ) self.should_poll = True def stop_poller( self ): # Stop appending into self.data #self.reader.stop() self.should_poll = False def run( self ): rospy.logout( 'rfid_poller: Starting' ) while self.should_run and not rospy.is_shutdown(): if self.should_poll: left = self.reader.read('EleLeftEar')[-1] success, x, y, ang = self.transform( 'EleLeftEar' ) if success: self.data.append( [left, [x,y,ang]] ) right = self.reader.read('EleRightEar')[-1] success, x, y, ang = self.transform( 'EleRightEar' ) if success: self.data.append( [right, [x,y,ang]] ) else: rospy.sleep( 0.050 ) try: # Shut it down to conserve power. Something of a race condition (exception) self.reader.stop() except: pass rospy.logout( 'rfid_poller: Exiting' ) def stop( self ): # Kill off the poller thread. self.should_run = False self.join(5) if (self.isAlive()): raise RuntimeError("rfid_poller: Unable to stop thread") # A more general form of this should be folded back into orient_node (rfid_people_following)! class Flapper( Thread ): def __init__( self, tagid = 'person '): Thread.__init__( self ) rospy.logout('Flapper: Initializing' ) rospy.wait_for_service( '/rfid_orient/flap' ) rospy.logout('Flapper: flap service ready.' ) self._flap = rospy.ServiceProxy( '/rfid_orient/flap', String_StringArr ) self.flap = lambda : self._flap( tagid ) self.should_run = True self.should_flap = False self.start() def start_flapper( self ): # Start appending into self.data #self.reader.track_mode( self.tagid ) self.should_flap = True def stop_flapper( self ): # Stop appending into self.data #self.reader.stop() self.should_flap = False def run( self ): rospy.logout( 'Flapper: Starting' ) r = rospy.Rate( 10 ) while self.should_run and not rospy.is_shutdown(): if self.should_flap: self.flap() else: r.sleep() rospy.logout( 'Flapper: Exiting' ) def stop( self ): # Kill off the poller thread. self.should_run = False self.join(15) if (self.isAlive()): raise RuntimeError("Flapper: Unable to stop thread") def navstack( x, y, ang ): try: rospy.logout( 'Requesting navstack move to <x,y,ang-deg> %3.3f %3.3f %3.3f.' % (x, y, math.degrees(ang)) ) client = actionlib.SimpleActionClient( 'move_base', MoveBaseAction ) client.wait_for_server() ps = PoseStamped() ps.header.frame_id = '/map' ps.header.stamp = rospy.Time(0) ps.pose.position.x = x ps.pose.position.y = y ps.pose.orientation = Quaternion( *tft.quaternion_from_euler( 0.0, 0.0, ang )) goal = MoveBaseGoal( ps ) client.send_goal( goal ) rospy.logout( 'Waiting for base to stop moving.' ) client.wait_for_result() rospy.logout( 'Successfully navigated to desired position.' ) return True except: rospy.logout( 'Navstack did not achieve desired position.' ) return False class RFIDSearch(): def __init__( self ): try: rospy.init_node( 'rfid_search' ) except: pass rospy.logout( 'rfid_search: Initializing.' ) rospy.wait_for_service( '/rfid_servo/servo' ) rospy.wait_for_service( '/rfid_orient/orient' ) rospy.wait_for_service( '/rfid_orient/flap' ) rospy.wait_for_service( '/rfid_demo/demo' ) #rospy.wait_for_service( '/rfid_gui/select' ) self.explore_act = actionlib.SimpleActionClient('explore', explore_hrl.msg.ExploreAction) self.explore_act.wait_for_server() rospy.logout( 'rfid_search: Done Initializing.' ) self._servo = rospy.ServiceProxy( '/rfid_servo/servo', StringInt32_Int32 ) self.follow1 = lambda : self._servo( 'person ', 1 ) # Stops at first obs self.follow = lambda : self._servo( 'person ', 0 ) # Runs forever self._demo = rospy.ServiceProxy( '/rfid_demo/demo', Empty ) self.demo = lambda : self._demo() self._servo_stop = rospy.ServiceProxy( '/rfid_servo/stop_next_obs', Int32_Int32 ) self.servo_toggle = lambda : self._servo_stop( 1 ) self._orient = rospy.ServiceProxy( '/rfid_orient/orient', String_Int32 ) self.orient = lambda tagid: self._orient( tagid ) self.rp = rfid_poller('person ') self.flapper = Flapper() rospy.logout( 'rfid_search: ready to go!' ) def wait_for_finish( self, radius = 2.0 ): print 'Starting RFID tag scanning' self.rp.start_poller() self.flapper.start_flapper() rospy.sleep( 0.3 ) print 'Starting Search' goal = explore_hrl.msg.ExploreGoal( radius = radius ) self.explore_act.send_goal(goal) rospy.sleep( 0.5 ) self.explore_act.wait_for_result() res = self.explore_act.get_result() print 'Search Complete' print 'Disabling RFID scanning' self.flapper.stop_flapper() self.rp.stop_poller() print 'Computing Best Position' readings = self.rp.data print readings rr = list( self.rp.data ) # rfid_reads: [ [rssi,[x,y,ang]], ...] rssi = [ r for r,vec in rr ] max_rssi, max_pose = rr[ np.argmax( rssi ) ] print 'Moving to best Position: ', max_pose navstack( *max_pose ) print 'Executing Remainder of Demo' if (os.environ.has_key('ROBOT') and os.environ['ROBOT'] == 'sim'): self.follow1() # Only do servoing in simulation else: try: self.demo() # Run the full demo IRL except: # for some reason, NoneType throws exception... pass print 'Shutting down threads' self.rp.stop() self.flapper.stop() if __name__ == '__main__': rs = RFIDSearch() time.sleep( 3 ) rs.wait_for_finish( radius = 1.7 ) #print rs.flap() # while True: # print 'DoneSearching: ', rs.doneSearching()
[ [ 1, 0, 0.0104, 0.0035, 0, 0.66, 0, 796, 0, 1, 0, 0, 796, 0, 0 ], [ 8, 0, 0.0138, 0.0035, 0, 0.66, 0.0303, 630, 3, 1, 0, 0, 0, 0, 1 ], [ 8, 0, 0.0173, 0.0035, 0, 0....
[ "import roslib;", "roslib.load_manifest('rfid_people_following')", "roslib.load_manifest('std_srvs')", "roslib.load_manifest('explore_hrl')", "roslib.load_manifest('move_base_msgs')", "roslib.load_manifest('actionlib')", "roslib.load_manifest('geometry_msgs')", "roslib.load_manifest('tf')", "roslib....
#!/usr/bin/python import roslib roslib.load_manifest('explore_hrl') import rospy import actionlib import explore_hrl.msg def explore_client( radius ): client = actionlib.SimpleActionClient('explore', explore_hrl.msg.ExploreAction) # Waits until the action server has started up and started # listening for goals. client.wait_for_server() # Creates a goal to send to the action server. goal = explore_hrl.msg.ExploreGoal( radius = radius ) # Sends the goal to the action server. client.send_goal(goal) r = rospy.Rate( 1 ) t0 = rospy.Time.now().to_time() # while True: # print 'State: ', client.get_state() # r.sleep() # Waits for the server to finish performing the action. client.wait_for_result() # Prints out the result of executing the action #return client.get_result() # A FibonacciResult return client.get_state() if __name__ == '__main__': import optparse p = optparse.OptionParser() p.add_option('-r', action='store', type='float', dest='radius', help='Sensing radius', default=2.0) opt, args = p.parse_args() try: # Initializes a rospy node so that the SimpleActionClient can # publish and subscribe over ROS. rospy.init_node('explore_client_py') result = explore_client( opt.radius ) if result == actionlib.GoalStatus.SUCCEEDED: print 'SUCCEEDED' else: print 'FAILED' except rospy.ROSInterruptException: print "program interrupted before completion"
[ [ 1, 0, 0.0577, 0.0192, 0, 0.66, 0, 796, 0, 1, 0, 0, 796, 0, 0 ], [ 8, 0, 0.0769, 0.0192, 0, 0.66, 0.1667, 630, 3, 1, 0, 0, 0, 0, 1 ], [ 1, 0, 0.0962, 0.0192, 0, 0....
[ "import roslib", "roslib.load_manifest('explore_hrl')", "import rospy", "import actionlib", "import explore_hrl.msg", "def explore_client( radius ):\n client = actionlib.SimpleActionClient('explore', explore_hrl.msg.ExploreAction)\n\n # Waits until the action server has started up and started\n #...
#!/usr/bin/python2.6 # # Copyright 2011 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Build the BITE Extension.""" __author__ = 'ralphj@google.com (Julie Ralph)' import logging import optparse import os import shutil import subprocess import urllib import zipfile CHECKOUT_ACE_COMMAND = ('git clone git://github.com/ajaxorg/ace.git') CHECKOUT_CLOSURE_COMMAND = ('svn checkout http://closure-library.googlecode.com' '/svn/trunk/ closure-library') CHECKOUT_SELENIUM_COMMAND = ('svn checkout http://selenium.googlecode.com' '/svn/trunk/javascript/atoms selenium-atoms-lib') CLOSURE_COMPILER_URL = ('http://closure-compiler.googlecode.com/files/' 'compiler-latest.zip') SOY_COMPILER_URL = ('http://closure-templates.googlecode.com/files/' 'closure-templates-for-javascript-latest.zip') SOYDATA_URL = ('http://closure-templates.googlecode.com/svn/trunk/javascript/' 'soydata.js') COMPILE_CLOSURE_COMMAND = ('closure-library/closure/bin/build/closurebuilder.py' ' --root=src' ' --root=closure-library' ' --root=build_gen' ' --root=selenium-atoms-lib' ' --input=%(input)s' ' --output_mode=compiled' ' --output_file=%(output)s' ' --compiler_jar=compiler.jar') SOY_COMPILER_COMMAND = ('java -jar SoyToJsSrcCompiler.jar' ' --shouldProvideRequireSoyNamespaces' ' --outputPathFormat %(output)s' ' %(file)s') class ClosureError(Exception): pass def BuildClosureScript(input_filename, output_filename): """Build a compiled closure script based on the given input file. Args: input_filename: A string representing the name of the input script to compile output_filename: A string representing the name of the output script. Raises: ClosureError: If closure fails to compile the given input file. """ result = ExecuteCommand( COMPILE_CLOSURE_COMMAND % { 'input': input_filename, 'output': output_filename}) if result or not os.path.exists(output_filename): raise ClosureError('Failed while compiling %s.' % input_filename) def BuildSoyJs(input_file): """Builds a javascript file from a soy file. Args: input_file: A path to the soy file to compile into JavaScript. The js file will be stored in build_gen/{FILENAME}.soy.js Raises: ClosureError: If the soy compiler fails to compile. """ output_name = os.path.join('build_gen', '%s.js' % input_file) result = ExecuteCommand( SOY_COMPILER_COMMAND % { 'file': input_file, 'output': output_name}) if result or not os.path.exists(output_name): raise ClosureError('Failed while compiling the soy file %s.' % input_file) def Clean(): if os.path.exists('clean'): shutil.rmtree('build') if os.path.exists('build_gen'): shutil.rmtree('build_gen') def ExecuteCommand(command): """Execute the given command and return the output. Args: command: A string representing the command to execute. Returns: The return code of the process. """ print 'Running command: %s' % command process = subprocess.Popen(command.split(' '), stdout=subprocess.PIPE, stderr=subprocess.PIPE) results = process.communicate() if process.returncode: logging.error(results[1]) return process.returncode def SetupAce(): """Setup the Ace library. Checkout the Ace library using git. Raises: ClosureError: If the setup fails. """ if not os.path.exists('ace'): ExecuteCommand(CHECKOUT_ACE_COMMAND) if not os.path.exists('ace'): logging.error('Could not checkout ACE from github.') raise ClosureError('Could not set up ACE.') def SetupClosure(): """Setup the closure library and compiler. Checkout the closure library using svn if it doesn't exist. Also, download the closure compiler. Raises: ClosureError: If the setup fails. """ # Set up the svn repo for closure if it doesn't exist. if not os.path.exists('closure-library'): ExecuteCommand(CHECKOUT_CLOSURE_COMMAND) if not os.path.exists('closure-library'): logging.error(('Could not check out the closure library from svn. ' 'Please check out the closure library to the ' '"closure-library" directory.')) raise ClosureError('Could not set up the closure library.') # Download the compiler jar if it doesn't exist. if not os.path.exists('compiler.jar'): (compiler_zip, _) = urllib.urlretrieve(CLOSURE_COMPILER_URL) compiler_zipfile = zipfile.ZipFile(compiler_zip) compiler_zipfile.extract('compiler.jar') if not os.path.exists('compiler.jar'): logging.error('Could not download the closure compiler jar.') raise ClosureError('Could not find the closure compiler.') # Download the soy compiler jar if it doesn't exist. if (not os.path.exists('SoyToJsSrcCompiler.jar') or not os.path.exists('build_gen/soyutils_usegoog.js')): (soy_compiler_zip, _) = urllib.urlretrieve(SOY_COMPILER_URL) soy_compiler_zipfile = zipfile.ZipFile(soy_compiler_zip) soy_compiler_zipfile.extract('SoyToJsSrcCompiler.jar') soy_compiler_zipfile.extract('soyutils_usegoog.js', 'build_gen') if (not os.path.exists('SoyToJsSrcCompiler.jar') or not os.path.exists('build_gen/soyutils_usegoog.js')): logging.error('Could not download the soy compiler jar.') raise ClosureError('Could not find the soy compiler.') # Download required soydata file, which is required for soyutils_usegoog.js # to work. if not os.path.exists('build_gen/soydata.js'): urllib.urlretrieve(SOYDATA_URL, 'build_gen/soydata.js') if not os.path.exists('build_gen/soydata.js'): logging.error('Could not download soydata.js.') raise ClosureError('Could not fine soydata.js') def SetupSelenium(): """Setup the selenium library. Checkout necessary files from the selenium library using svn, if they don't exist. Raises: ClosureError: If the setup fails. """ if not os.path.exists('selenium-atoms-lib/bot.js'): ExecuteCommand(CHECKOUT_SELENIUM_COMMAND) if not os.path.exists('selenium-atoms-lib/bot.js'): logging.error('Could not download the selenium library.') raise ClosureError('Could not find the selenium library.') def main(): usage = 'usage: %prog [options]' parser = optparse.OptionParser(usage) parser.add_option('--clean', dest='build_clean', action='store_true', default=False, help='Clean the build directories.') (options, _) = parser.parse_args() if options.build_clean: Clean() exit() # Set up the directories that will be built into. if not os.path.exists('build'): os.mkdir('build') if not os.path.exists('build/options'): os.mkdir('build/options') if not os.path.exists('build_gen'): os.mkdir('build_gen') # Get external resources. SetupClosure() SetupSelenium() SetupAce() # Compile the closure scripts. soy_files = ['consoles.soy', 'rpfconsole.soy', 'rpf_dialogs.soy', 'locatorsupdater.soy', 'newbug_console.soy', 'newbug_type_selector.soy', 'popup.soy'] for soy_filename in soy_files: BuildSoyJs(os.path.join('src', soy_filename)) js_targets = {'background.js': 'background_script.js', 'content.js': 'content_script.js', 'getactioninfo.js': 'getactioninfo_script.js', 'console.js': 'console_script.js', 'elementhelper.js': 'elementhelper_script.js', 'popup.js': 'popup_script.js', 'options/page.js': 'options_script.js'} for target in js_targets: BuildClosureScript(os.path.join('src', target), os.path.join('build', js_targets[target])) # Copy over the static resources if os.path.exists('build/styles'): shutil.rmtree('build/styles') shutil.copytree('src/styles', 'build/styles') if os.path.exists('build/imgs'): shutil.rmtree('build/imgs') shutil.copytree('src/imgs', 'build/imgs') static_files = ['src/background.html', 'src/console.html', 'src/options/options.html', 'src/popup.html', 'manifest.json'] for static_file in static_files: shutil.copy(static_file, 'build') # Copy the required ACE files. if os.path.exists('build/ace'): shutil.rmtree('build/ace') shutil.copytree('ace/build/src', 'build/ace') if __name__ == '__main__': main()
[ [ 8, 0, 0.065, 0.0036, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 14, 0, 0.0722, 0.0036, 0, 0.66, 0.0385, 777, 1, 0, 0, 0, 0, 3, 0 ], [ 1, 0, 0.0794, 0.0036, 0, 0.66, ...
[ "\"\"\"Build the BITE Extension.\"\"\"", "__author__ = 'ralphj@google.com (Julie Ralph)'", "import logging", "import optparse", "import os", "import shutil", "import subprocess", "import urllib", "import zipfile", "CHECKOUT_ACE_COMMAND = ('git clone git://github.com/ajaxorg/ace.git')", "CHECKOUT...
#==================================================================== # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # ==================================================================== # # This software consists of voluntary contributions made by many # individuals on behalf of the Apache Software Foundation. For more # information on the Apache Software Foundation, please see # <http://www.apache.org/>. # import os import re import tempfile import shutil ignore_pattern = re.compile('^(.svn|target|bin|classes)') java_pattern = re.compile('^.*\.java') annot_pattern = re.compile('import org\.apache\.http\.annotation\.') def process_dir(dir): files = os.listdir(dir) for file in files: f = os.path.join(dir, file) if os.path.isdir(f): if not ignore_pattern.match(file): process_dir(f) else: if java_pattern.match(file): process_source(f) def process_source(filename): tmp = tempfile.mkstemp() tmpfd = tmp[0] tmpfile = tmp[1] try: changed = False dst = os.fdopen(tmpfd, 'w') try: src = open(filename) try: for line in src: if annot_pattern.match(line): changed = True line = line.replace('import org.apache.http.annotation.', 'import net.jcip.annotations.') dst.write(line) finally: src.close() finally: dst.close(); if changed: shutil.move(tmpfile, filename) else: os.remove(tmpfile) except: os.remove(tmpfile) process_dir('.')
[ [ 1, 0, 0.3514, 0.0135, 0, 0.66, 0, 688, 0, 1, 0, 0, 688, 0, 0 ], [ 1, 0, 0.3649, 0.0135, 0, 0.66, 0.1111, 540, 0, 1, 0, 0, 540, 0, 0 ], [ 1, 0, 0.3784, 0.0135, 0, ...
[ "import os", "import re", "import tempfile", "import shutil", "ignore_pattern = re.compile('^(.svn|target|bin|classes)')", "java_pattern = re.compile('^.*\\.java')", "annot_pattern = re.compile('import org\\.apache\\.http\\.annotation\\.')", "def process_dir(dir):\n files = os.listdir(dir)\n for...
#!/usr/bin/python2.6 # # Copyright 2011 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Build the BITE Extension.""" __author__ = 'ralphj@google.com (Julie Ralph)' import logging import optparse import os import shutil import subprocess import urllib import zipfile CHECKOUT_ACE_COMMAND = ('git clone git://github.com/ajaxorg/ace.git') CHECKOUT_CLOSURE_COMMAND = ('svn checkout http://closure-library.googlecode.com' '/svn/trunk/ closure-library') CHECKOUT_SELENIUM_COMMAND = ('svn checkout http://selenium.googlecode.com' '/svn/trunk/javascript/atoms selenium-atoms-lib') CLOSURE_COMPILER_URL = ('http://closure-compiler.googlecode.com/files/' 'compiler-latest.zip') SOY_COMPILER_URL = ('http://closure-templates.googlecode.com/files/' 'closure-templates-for-javascript-latest.zip') SOYDATA_URL = ('http://closure-templates.googlecode.com/svn/trunk/javascript/' 'soydata.js') COMPILE_CLOSURE_COMMAND = ('closure-library/closure/bin/build/closurebuilder.py' ' --root=src' ' --root=closure-library' ' --root=build_gen' ' --root=selenium-atoms-lib' ' --input=%(input)s' ' --output_mode=compiled' ' --output_file=%(output)s' ' --compiler_jar=compiler.jar') SOY_COMPILER_COMMAND = ('java -jar SoyToJsSrcCompiler.jar' ' --shouldProvideRequireSoyNamespaces' ' --outputPathFormat %(output)s' ' %(file)s') class ClosureError(Exception): pass def BuildClosureScript(input_filename, output_filename): """Build a compiled closure script based on the given input file. Args: input_filename: A string representing the name of the input script to compile output_filename: A string representing the name of the output script. Raises: ClosureError: If closure fails to compile the given input file. """ result = ExecuteCommand( COMPILE_CLOSURE_COMMAND % { 'input': input_filename, 'output': output_filename}) if result or not os.path.exists(output_filename): raise ClosureError('Failed while compiling %s.' % input_filename) def BuildSoyJs(input_file): """Builds a javascript file from a soy file. Args: input_file: A path to the soy file to compile into JavaScript. The js file will be stored in build_gen/{FILENAME}.soy.js Raises: ClosureError: If the soy compiler fails to compile. """ output_name = os.path.join('build_gen', '%s.js' % input_file) result = ExecuteCommand( SOY_COMPILER_COMMAND % { 'file': input_file, 'output': output_name}) if result or not os.path.exists(output_name): raise ClosureError('Failed while compiling the soy file %s.' % input_file) def Clean(): if os.path.exists('clean'): shutil.rmtree('build') if os.path.exists('build_gen'): shutil.rmtree('build_gen') def ExecuteCommand(command): """Execute the given command and return the output. Args: command: A string representing the command to execute. Returns: The return code of the process. """ print 'Running command: %s' % command process = subprocess.Popen(command.split(' '), stdout=subprocess.PIPE, stderr=subprocess.PIPE) results = process.communicate() if process.returncode: logging.error(results[1]) return process.returncode def SetupAce(): """Setup the Ace library. Checkout the Ace library using git. Raises: ClosureError: If the setup fails. """ if not os.path.exists('ace'): ExecuteCommand(CHECKOUT_ACE_COMMAND) if not os.path.exists('ace'): logging.error('Could not checkout ACE from github.') raise ClosureError('Could not set up ACE.') def SetupClosure(): """Setup the closure library and compiler. Checkout the closure library using svn if it doesn't exist. Also, download the closure compiler. Raises: ClosureError: If the setup fails. """ # Set up the svn repo for closure if it doesn't exist. if not os.path.exists('closure-library'): ExecuteCommand(CHECKOUT_CLOSURE_COMMAND) if not os.path.exists('closure-library'): logging.error(('Could not check out the closure library from svn. ' 'Please check out the closure library to the ' '"closure-library" directory.')) raise ClosureError('Could not set up the closure library.') # Download the compiler jar if it doesn't exist. if not os.path.exists('compiler.jar'): (compiler_zip, _) = urllib.urlretrieve(CLOSURE_COMPILER_URL) compiler_zipfile = zipfile.ZipFile(compiler_zip) compiler_zipfile.extract('compiler.jar') if not os.path.exists('compiler.jar'): logging.error('Could not download the closure compiler jar.') raise ClosureError('Could not find the closure compiler.') # Download the soy compiler jar if it doesn't exist. if (not os.path.exists('SoyToJsSrcCompiler.jar') or not os.path.exists('build_gen/soyutils_usegoog.js')): (soy_compiler_zip, _) = urllib.urlretrieve(SOY_COMPILER_URL) soy_compiler_zipfile = zipfile.ZipFile(soy_compiler_zip) soy_compiler_zipfile.extract('SoyToJsSrcCompiler.jar') soy_compiler_zipfile.extract('soyutils_usegoog.js', 'build_gen') if (not os.path.exists('SoyToJsSrcCompiler.jar') or not os.path.exists('build_gen/soyutils_usegoog.js')): logging.error('Could not download the soy compiler jar.') raise ClosureError('Could not find the soy compiler.') # Download required soydata file, which is required for soyutils_usegoog.js # to work. if not os.path.exists('build_gen/soydata.js'): urllib.urlretrieve(SOYDATA_URL, 'build_gen/soydata.js') if not os.path.exists('build_gen/soydata.js'): logging.error('Could not download soydata.js.') raise ClosureError('Could not fine soydata.js') def SetupSelenium(): """Setup the selenium library. Checkout necessary files from the selenium library using svn, if they don't exist. Raises: ClosureError: If the setup fails. """ if not os.path.exists('selenium-atoms-lib/bot.js'): ExecuteCommand(CHECKOUT_SELENIUM_COMMAND) if not os.path.exists('selenium-atoms-lib/bot.js'): logging.error('Could not download the selenium library.') raise ClosureError('Could not find the selenium library.') def main(): usage = 'usage: %prog [options]' parser = optparse.OptionParser(usage) parser.add_option('--clean', dest='build_clean', action='store_true', default=False, help='Clean the build directories.') (options, _) = parser.parse_args() if options.build_clean: Clean() exit() # Set up the directories that will be built into. if not os.path.exists('build'): os.mkdir('build') if not os.path.exists('build/options'): os.mkdir('build/options') if not os.path.exists('build_gen'): os.mkdir('build_gen') # Get external resources. SetupClosure() SetupSelenium() SetupAce() # Compile the closure scripts. soy_files = ['consoles.soy', 'rpfconsole.soy', 'rpf_dialogs.soy', 'locatorsupdater.soy', 'newbug_console.soy', 'newbug_type_selector.soy', 'popup.soy'] for soy_filename in soy_files: BuildSoyJs(os.path.join('src', soy_filename)) js_targets = {'background.js': 'background_script.js', 'content.js': 'content_script.js', 'getactioninfo.js': 'getactioninfo_script.js', 'console.js': 'console_script.js', 'elementhelper.js': 'elementhelper_script.js', 'popup.js': 'popup_script.js', 'options/page.js': 'options_script.js'} for target in js_targets: BuildClosureScript(os.path.join('src', target), os.path.join('build', js_targets[target])) # Copy over the static resources if os.path.exists('build/styles'): shutil.rmtree('build/styles') shutil.copytree('src/styles', 'build/styles') if os.path.exists('build/imgs'): shutil.rmtree('build/imgs') shutil.copytree('src/imgs', 'build/imgs') static_files = ['src/background.html', 'src/console.html', 'src/options/options.html', 'src/popup.html', 'manifest.json'] for static_file in static_files: shutil.copy(static_file, 'build') # Copy the required ACE files. if os.path.exists('build/ace'): shutil.rmtree('build/ace') shutil.copytree('ace/build/src', 'build/ace') if __name__ == '__main__': main()
[ [ 8, 0, 0.065, 0.0036, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 14, 0, 0.0722, 0.0036, 0, 0.66, 0.0385, 777, 1, 0, 0, 0, 0, 3, 0 ], [ 1, 0, 0.0794, 0.0036, 0, 0.66, ...
[ "\"\"\"Build the BITE Extension.\"\"\"", "__author__ = 'ralphj@google.com (Julie Ralph)'", "import logging", "import optparse", "import os", "import shutil", "import subprocess", "import urllib", "import zipfile", "CHECKOUT_ACE_COMMAND = ('git clone git://github.com/ajaxorg/ace.git')", "CHECKOUT...
import os THIS_PATH = os.path.dirname(__file__) GOLDEN_OUTPUT = os.path.join(THIS_PATH, 'golden_suite', 'output.xml') GOLDEN_OUTPUT2 = os.path.join(THIS_PATH, 'golden_suite', 'output2.xml') GOLDEN_JS = os.path.join(THIS_PATH, 'golden_suite', 'expected.js')
[ [ 1, 0, 0.1429, 0.1429, 0, 0.66, 0, 688, 0, 1, 0, 0, 688, 0, 0 ], [ 14, 0, 0.4286, 0.1429, 0, 0.66, 0.25, 832, 3, 1, 0, 0, 959, 10, 1 ], [ 14, 0, 0.5714, 0.1429, 0, ...
[ "import os", "THIS_PATH = os.path.dirname(__file__)", "GOLDEN_OUTPUT = os.path.join(THIS_PATH, 'golden_suite', 'output.xml')", "GOLDEN_OUTPUT2 = os.path.join(THIS_PATH, 'golden_suite', 'output2.xml')", "GOLDEN_JS = os.path.join(THIS_PATH, 'golden_suite', 'expected.js')" ]
#!/usr/bin/env python import fileinput import os import sys import robot from robot.result.jsparser import create_datamodel_from BASEDIR = os.path.dirname(__file__) def run_robot(outputdirectory, testdata, loglevel='INFO'): robot.run(testdata, log='NONE', report='NONE', tagstatlink=['force:http://google.com:<kuukkeli&gt;', 'i*:http://%1/:Title of i%1'], tagdoc=['test:this_is_*my_bold*_test', 'IX:*Combined* & escaped <&lt; tag doc'], tagstatcombine=['fooANDi*:zap', 'i?:IX'], critical=[], noncritical=[], outputdir=outputdirectory, loglevel=loglevel) def create_jsdata(output_xml_file, target): model = create_datamodel_from(output_xml_file) model.set_settings({'logURL': 'log.html', 'reportURL': 'report.html', 'background': {'fail': 'DeepPink'}}) with open(target, 'w') as output: model.write_to(output) def replace_all(file,searchExp,replaceExp): for line in fileinput.input(file, inplace=1): if searchExp in line: line = line.replace(searchExp,replaceExp) sys.stdout.write(line) def create(input, target, targetName, loglevel='INFO'): run_robot(BASEDIR, input, loglevel) create_jsdata('output.xml', target) replace_all(target, 'window.output', 'window.' + targetName) if __name__ == '__main__': create('Suite.txt', 'Suite.js', 'suiteOutput') create('SetupsAndTeardowns.txt', 'SetupsAndTeardowns.js', 'setupsAndTeardownsOutput') create('Messages.txt', 'Messages.js', 'messagesOutput') create('teardownFailure', 'TeardownFailure.js', 'teardownFailureOutput') create(os.path.join('teardownFailure', 'PassingFailing.txt'), 'PassingFailing.js', 'passingFailingOutput') create('TestsAndKeywords.txt', 'TestsAndKeywords.js', 'testsAndKeywordsOutput') create('.', 'allData.js', 'allDataOutput')
[ [ 1, 0, 0.0612, 0.0204, 0, 0.66, 0, 286, 0, 1, 0, 0, 286, 0, 0 ], [ 1, 0, 0.0816, 0.0204, 0, 0.66, 0.1, 688, 0, 1, 0, 0, 688, 0, 0 ], [ 1, 0, 0.102, 0.0204, 0, 0.66...
[ "import fileinput", "import os", "import sys", "import robot", "from robot.result.jsparser import create_datamodel_from", "BASEDIR = os.path.dirname(__file__)", "def run_robot(outputdirectory, testdata, loglevel='INFO'):\n robot.run(testdata, log='NONE', report='NONE',\n tagstatlink=['fo...
#!/usr/bin/env python import sys import os from distutils.core import setup import robot_postinstall execfile(os.path.join(os.path.dirname(__file__),'src','robot','version.py')) # Maximum width in Windows installer seems to be 70 characters -------| DESCRIPTION = """ Robot Framework is a generic test automation framework for acceptance testing and acceptance test-driven development (ATDD). It has easy-to-use tabular test data syntax and utilizes the keyword-driven testing approach. Its testing capabilities can be extended by test libraries implemented either with Python or Java, and users can create new keywords from existing ones using the same syntax that is used for creating test cases. """[1:-1] CLASSIFIERS = """ Development Status :: 5 - Production/Stable License :: OSI Approved :: Apache Software License Operating System :: OS Independent Programming Language :: Python Topic :: Software Development :: Testing """[1:-1] PACKAGES = ['robot', 'robot.api', 'robot.common', 'robot.conf', 'robot.libraries', 'robot.output', 'robot.parsing', 'robot.result', 'robot.running', 'robot.utils', 'robot.variables'] SCRIPT_NAMES = ['pybot', 'jybot', 'rebot'] if os.name == 'java': SCRIPT_NAMES.remove('pybot') def main(): inst_scripts = [ os.path.join('src','bin',name) for name in SCRIPT_NAMES ] if 'bdist_wininst' in sys.argv: inst_scripts = [ script+'.bat' for script in inst_scripts ] inst_scripts.append('robot_postinstall.py') elif os.sep == '\\': inst_scripts = [ script+'.bat' for script in inst_scripts ] if 'bdist_egg' in sys.argv: package_path = os.path.dirname(sys.argv[0]) robot_postinstall.egg_preinstall(package_path, inst_scripts) # Let distutils take care of most of the setup dist = setup( name = 'robotframework', version = get_version(sep='-'), author = 'Robot Framework Developers', author_email = 'robotframework-devel@googlegroups.com', url = 'http://robotframework.org', license = 'Apache License 2.0', description = 'A generic test automation framework', long_description = DESCRIPTION, keywords = 'robotframework testing testautomation atdd', platforms = 'any', classifiers = CLASSIFIERS.splitlines(), package_dir = {'': 'src'}, package_data = {'robot': ['webcontent/*.html', 'webcontent/*.css', 'webcontent/*js', 'webcontent/lib/*.js']}, packages = PACKAGES, scripts = inst_scripts, ) if 'install' in sys.argv: absnorm = lambda path: os.path.abspath(os.path.normpath(path)) script_dir = absnorm(dist.command_obj['install_scripts'].install_dir) module_dir = absnorm(dist.command_obj['install_lib'].install_dir) robot_dir = os.path.join(module_dir, 'robot') script_names = [ os.path.basename(name) for name in inst_scripts ] robot_postinstall.generic_install(script_names, script_dir, robot_dir) if __name__ == "__main__": main()
[ [ 1, 0, 0.0385, 0.0128, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.0513, 0.0128, 0, 0.66, 0.0909, 688, 0, 1, 0, 0, 688, 0, 0 ], [ 1, 0, 0.0641, 0.0128, 0, ...
[ "import sys", "import os", "from distutils.core import setup", "import robot_postinstall", "execfile(os.path.join(os.path.dirname(__file__),'src','robot','version.py'))", "DESCRIPTION = \"\"\"\nRobot Framework is a generic test automation framework for acceptance\ntesting and acceptance test-driven develo...
#!/usr/bin/env python """A script for running Robot Framework's acceptance tests. Usage: run_atests.py interpreter [options] datasource(s) Data sources are paths to directories or files under `robot` folder. Available options are the same that can be used with Robot Framework. See its help (e.g. `pybot --help`) for more information. The specified interpreter is used by acceptance tests under `robot` to run test cases under `testdata`. It can be simply `python` or `jython` (if they are in PATH) or to a path a selected interpreter (e.g. `/usr/bin/python26`). Note that this script itself must always be executed with Python. Examples: $ atest/run_atests.py python --test example atest/robot $ atest/run_atests.py /usr/bin/jython25 atest/robot/tags/tag_doc.txt """ import signal import subprocess import os.path import shutil import glob import sys from zipfile import ZipFile, ZIP_DEFLATED CURDIR = os.path.dirname(os.path.abspath(__file__)) RESULTDIR = os.path.join(CURDIR, 'results') sys.path.insert(0, os.path.join(CURDIR, '..', 'src')) import robot ARGUMENTS = ' '.join(''' --doc RobotSPFrameworkSPacceptanceSPtests --reporttitle RobotSPFrameworkSPTestSPReport --logtitle RobotSPFrameworkSPTestSPLog --metadata Interpreter:%(INTERPRETER)s --metadata Platform:%(PLATFORM)s --variable INTERPRETER:%(INTERPRETER)s --variable STANDALONE_JYTHON:NO --pythonpath %(PYTHONPATH)s --include %(RUNNER)s --outputdir %(OUTPUTDIR)s --output output.xml --report report.html --log log.html --splitlog --escape space:SP --escape star:STAR --escape paren1:PAR1 --escape paren2:PAR2 --critical regression --noncritical to_be_clarified --noncritical static_html_checks --SuiteStatLevel 3 --TagStatCombine jybotNOTpybot --TagStatCombine pybotNOTjybot --TagStatExclude pybot --TagStatExclude jybot '''.strip().splitlines()) def atests(interpreter, *params): if os.path.isdir(RESULTDIR): shutil.rmtree(RESULTDIR) runner = ('jython' in os.path.basename(interpreter) and 'jybot' or 'pybot') args = ARGUMENTS % { 'PYTHONPATH' : os.path.join(CURDIR, 'resources'), 'OUTPUTDIR' : RESULTDIR, 'INTERPRETER': interpreter, 'PLATFORM': sys.platform, 'RUNNER': runner } if os.name == 'nt': args += ' --exclude nonwindows' if sys.platform == 'darwin' and runner == 'pybot': args += ' --exclude nonmacpython' runner = os.path.join(os.path.dirname(robot.__file__), 'runner.py') command = '%s %s %s %s' % (sys.executable, runner, args, ' '.join(params)) print 'Running command\n%s\n' % command sys.stdout.flush() signal.signal(signal.SIGINT, signal.SIG_IGN) return subprocess.call(command.split()) def buildbot(interpreter, *params): params = '--log NONE --report NONE --SplitOutputs 1'.split() + list(params) rc = atests(interpreter, *params) zippath = os.path.join(RESULTDIR, 'outputs.zip') zipfile = ZipFile(zippath, 'w', compression=ZIP_DEFLATED) for output in glob.glob(os.path.join(RESULTDIR, '*.xml')): zipfile.write(output, os.path.basename(output)) zipfile.close() print 'Archive:', zippath return rc if __name__ == '__main__': if len(sys.argv) == 1 or '--help' in sys.argv: print __doc__ rc = 251 elif sys.argv[1] == 'buildbot': rc = buildbot(*sys.argv[2:]) else: rc = atests(*sys.argv[1:]) sys.exit(rc)
[ [ 8, 0, 0.1062, 0.1681, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.2035, 0.0088, 0, 0.66, 0.0667, 621, 0, 1, 0, 0, 621, 0, 0 ], [ 1, 0, 0.2124, 0.0088, 0, 0.66...
[ "\"\"\"A script for running Robot Framework's acceptance tests.\n\nUsage: run_atests.py interpreter [options] datasource(s)\n\nData sources are paths to directories or files under `robot` folder.\n\nAvailable options are the same that can be used with Robot Framework.\nSee its help (e.g. `pybot --help`) for more i...
import subprocess import os import signal import ctypes import time class ProcessManager(object): def __init__(self): self._process = None self._stdout = '' self._stderr = '' def start_process(self, *args): args = args[0].split() + list(args[1:]) self._process = subprocess.Popen(args, stderr=subprocess.PIPE, stdout=subprocess.PIPE) self._stdout = '' self._stderr = '' def send_terminate(self, signal_name): if os.name != 'nt': os.kill(self._process.pid, getattr(signal, signal_name)) else: self._set_handler_to_ignore_one_sigint() ctypes.windll.kernel32.GenerateConsoleCtrlEvent(0, 0) def _set_handler_to_ignore_one_sigint(self): orig_handler = signal.getsignal(signal.SIGINT) signal.signal(signal.SIGINT, lambda signum, frame: signal.signal(signal.SIGINT, orig_handler)) def get_stdout(self): self.wait_until_finished() return self._stdout def get_stderr(self): self.wait_until_finished() return self._stderr def log_stdout_and_stderr(self): print "stdout: ", self._process.stdout.read() print "stderr: ", self._process.stderr.read() def wait_until_finished(self): if self._process.returncode is None: self._stdout, self._stderr = self._process.communicate() def busy_sleep(self, seconds): max_time = time.time() + int(seconds) while time.time() < max_time: pass def get_jython_path(self): jython_home = os.getenv('JYTHON_HOME') if not jython_home: raise RuntimeError('This test requires JYTHON_HOME environment variable to be set.') return '%s -Dpython.home=%s -classpath %s org.python.util.jython' \ % (self._get_java(), jython_home, self._get_classpath(jython_home)) def _get_java(self): java_home = os.getenv('JAVA_HOME') if not java_home: return 'java' if java_home.startswith('"') and java_home.endswith('"'): java_home = java_home[1:-1] return os.path.join(java_home, 'bin', 'java') def _get_classpath(self, jython_home): jython_jar = os.path.join(jython_home, 'jython.jar') return jython_jar + os.pathsep + os.getenv('CLASSPATH','')
[ [ 1, 0, 0.0137, 0.0137, 0, 0.66, 0, 394, 0, 1, 0, 0, 394, 0, 0 ], [ 1, 0, 0.0274, 0.0137, 0, 0.66, 0.2, 688, 0, 1, 0, 0, 688, 0, 0 ], [ 1, 0, 0.0411, 0.0137, 0, 0.6...
[ "import subprocess", "import os", "import signal", "import ctypes", "import time", "class ProcessManager(object):\n\n def __init__(self):\n self._process = None\n self._stdout = ''\n self._stderr = ''\n\n def start_process(self, *args):", " def __init__(self):\n self...
from robot.libraries.BuiltIn import BuiltIn BIN = BuiltIn() def start_keyword(*args): if BIN.get_variables()['${TESTNAME}'] == 'Listener Using BuiltIn': BIN.set_test_variable('${SET BY LISTENER}', 'quux')
[ [ 1, 0, 0.1111, 0.1111, 0, 0.66, 0, 588, 0, 1, 0, 0, 588, 0, 0 ], [ 14, 0, 0.3333, 0.1111, 0, 0.66, 0.5, 831, 3, 0, 0, 0, 961, 10, 1 ], [ 2, 0, 0.7778, 0.3333, 0, 0...
[ "from robot.libraries.BuiltIn import BuiltIn", "BIN = BuiltIn()", "def start_keyword(*args):\n if BIN.get_variables()['${TESTNAME}'] == 'Listener Using BuiltIn':\n BIN.set_test_variable('${SET BY LISTENER}', 'quux')", " if BIN.get_variables()['${TESTNAME}'] == 'Listener Using BuiltIn':\n B...
import os import tempfile import time class ListenAll: ROBOT_LISTENER_API_VERSION = '2' def __init__(self, *path): if not path: path = os.path.join(tempfile.gettempdir(), 'listen_all.txt') else: path = ':'.join(path) self.outfile = open(path, 'w') def start_suite(self, name, attrs): metastr = ' '.join(['%s: %s' % (k, v) for k, v in attrs['metadata'].items()]) self.outfile.write("SUITE START: %s '%s' [%s]\n" % (name, attrs['doc'], metastr)) def start_test(self, name, attrs): tags = [ str(tag) for tag in attrs['tags'] ] self.outfile.write("TEST START: %s '%s' %s\n" % (name, attrs['doc'], tags)) def start_keyword(self, name, attrs): args = [ str(arg) for arg in attrs['args'] ] self.outfile.write("KW START: %s %s\n" % (name, args)) def log_message(self, message): msg, level = self._check_message_validity(message) if level != 'TRACE' and 'Traceback' not in msg: self.outfile.write('LOG MESSAGE: [%s] %s\n' % (level, msg)) def message(self, message): msg, level = self._check_message_validity(message) if 'Settings' in msg: self.outfile.write('Got settings on level: %s\n' % level) def _check_message_validity(self, message): if message['html'] not in ['yes', 'no']: self.outfile.write('Log message has invalid `html` attribute %s' % message['html']) if not message['timestamp'].startswith(str(time.localtime()[0])): self.outfile.write('Log message has invalid timestamp %s' % message['timestamp']) return message['message'], message['level'] def end_keyword(self, name, attrs): self.outfile.write("KW END: %s\n" % (attrs['status'])) def end_test(self, name, attrs): if attrs['status'] == 'PASS': self.outfile.write('TEST END: PASS\n') else: self.outfile.write("TEST END: %s %s\n" % (attrs['status'], attrs['message'])) def end_suite(self, name, attrs): self.outfile.write('SUITE END: %s %s\n' % (attrs['status'], attrs['statistics'])) def output_file(self, path): self._out_file('Output', path) def report_file(self, path): self._out_file('Report', path) def log_file(self, path): self._out_file('Log', path) def debug_file(self, path): self._out_file('Debug', path) def _out_file(self, name, path): assert os.path.isabs(path) self.outfile.write('%s: %s\n' % (name, os.path.basename(path))) def close(self): self.outfile.write('Closing...\n') self.outfile.close()
[ [ 1, 0, 0.0122, 0.0122, 0, 0.66, 0, 688, 0, 1, 0, 0, 688, 0, 0 ], [ 1, 0, 0.0244, 0.0122, 0, 0.66, 0.3333, 516, 0, 1, 0, 0, 516, 0, 0 ], [ 1, 0, 0.0366, 0.0122, 0, ...
[ "import os", "import tempfile", "import time", "class ListenAll:\n\n ROBOT_LISTENER_API_VERSION = '2'\n\n def __init__(self, *path):\n if not path:\n path = os.path.join(tempfile.gettempdir(), 'listen_all.txt')\n else:", " ROBOT_LISTENER_API_VERSION = '2'", " def __ini...
import os import tempfile class OldListenAll: def __init__(self, *path): if not path: path = os.path.join(tempfile.gettempdir(), 'listen_all.txt') else: path = ':'.join(path) self.outfile = open(path, 'w') def start_suite(self, name, doc): self.outfile.write("SUITE START: %s '%s'\n" % (name, doc)) def start_test(self, name, doc, tags): tags = [str(tag) for tag in tags] self.outfile.write("TEST START: %s '%s' %s\n" % (name, doc, tags)) def start_keyword(self, name, args): args = [str(arg) for arg in args] self.outfile.write("KW START: %s %s\n" % (name, args)) def end_keyword(self, status): self.outfile.write("KW END: %s\n" % (status)) def end_test(self, status, message): if status == 'PASS': self.outfile.write('TEST END: PASS\n') else: self.outfile.write("TEST END: %s %s\n" % (status, message)) def end_suite(self, status, message): self.outfile.write('SUITE END: %s %s\n' % (status, message)) def output_file(self, path): self._out_file('Output', path) def report_file(self, path): self._out_file('Report', path) def log_file(self, path): self._out_file('Log', path) def debug_file(self, path): self._out_file('Debug', path) def _out_file(self, name, path): assert os.path.isabs(path) self.outfile.write('%s: %s\n' % (name, os.path.basename(path))) def close(self): self.outfile.write('Closing...\n') self.outfile.close()
[ [ 1, 0, 0.0182, 0.0182, 0, 0.66, 0, 688, 0, 1, 0, 0, 688, 0, 0 ], [ 1, 0, 0.0364, 0.0182, 0, 0.66, 0.5, 516, 0, 1, 0, 0, 516, 0, 0 ], [ 3, 0, 0.5455, 0.9273, 0, 0.6...
[ "import os", "import tempfile", "class OldListenAll:\n\n def __init__(self, *path):\n if not path:\n path = os.path.join(tempfile.gettempdir(), 'listen_all.txt')\n else:\n path = ':'.join(path)\n self.outfile = open(path, 'w')", " def __init__(self, *path):\n ...
import os import tempfile outpath = os.path.join(tempfile.gettempdir(), 'listen_by_module.txt') OUTFILE = open(outpath, 'w') ROBOT_LISTENER_API_VERSION = 2 def start_suite(name, attrs): metastr = ' '.join(['%s: %s' % (k, v) for k, v in attrs['metadata'].items()]) OUTFILE.write("SUITE START: %s '%s' [%s]\n" % (name, attrs['doc'], metastr)) def start_test(name, attrs): tags = [ str(tag) for tag in attrs['tags'] ] OUTFILE.write("TEST START: %s '%s' %s\n" % (name, attrs['doc'], tags)) def start_keyword(name, attrs): args = [ str(arg) for arg in attrs['args'] ] OUTFILE.write("KW START: %s %s\n" % (name, args)) def log_message(message): msg, level = message['message'], message['level'] if level != 'TRACE' and 'Traceback' not in msg: OUTFILE.write('LOG MESSAGE: [%s] %s\n' % (level, msg)) def message(message): msg, level = message['message'], message['level'] if 'Settings' in msg: OUTFILE.write('Got settings on level: %s\n' % level) def end_keyword(name, attrs): OUTFILE.write("KW END: %s\n" % (attrs['status'])) def end_test(name, attrs): if attrs['status'] == 'PASS': OUTFILE.write('TEST END: PASS\n') else: OUTFILE.write("TEST END: %s %s\n" % (attrs['status'], attrs['message'])) def end_suite(name, attrs): OUTFILE.write('SUITE END: %s %s\n' % (attrs['status'], attrs['statistics'])) def output_file(path): _out_file('Output', path) def report_file(path): _out_file('Report', path) def log_file(path): _out_file('Log', path) def debug_file(path): _out_file('Debug', path) def _out_file(name, path): assert os.path.isabs(path) OUTFILE.write('%s: %s\n' % (name, os.path.basename(path))) def close(): OUTFILE.write('Closing...\n') OUTFILE.close()
[ [ 1, 0, 0.0159, 0.0159, 0, 0.66, 0, 688, 0, 1, 0, 0, 688, 0, 0 ], [ 1, 0, 0.0317, 0.0159, 0, 0.66, 0.0556, 516, 0, 1, 0, 0, 516, 0, 0 ], [ 14, 0, 0.0635, 0.0159, 0, ...
[ "import os", "import tempfile", "outpath = os.path.join(tempfile.gettempdir(), 'listen_by_module.txt')", "OUTFILE = open(outpath, 'w')", "ROBOT_LISTENER_API_VERSION = 2", "def start_suite(name, attrs):\n metastr = ' '.join(['%s: %s' % (k, v) for k, v\n in attrs['metadata'].items(...
import os import tempfile class ListenSome: def __init__(self): outpath = os.path.join(tempfile.gettempdir(), 'listen_some.txt') self.outfile = open(outpath, 'w') def startTest(self, name, doc, tags): self.outfile.write(name + '\n') def endSuite(self, stat, msg): self.outfile.write(msg + '\n') def close(self): self.outfile.close() class WithArgs(object): def __init__(self, arg1, arg2='default'): outpath = os.path.join(tempfile.gettempdir(), 'listener_with_args.txt') outfile = open(outpath, 'a') outfile.write("I got arguments '%s' and '%s'\n" % (arg1, arg2)) outfile.close() class InvalidMethods: def start_suite(self, wrong, number, of, args, here): pass def end_suite(self, *args): raise RuntimeError("Here comes an exception!")
[ [ 1, 0, 0.0278, 0.0278, 0, 0.66, 0, 688, 0, 1, 0, 0, 688, 0, 0 ], [ 1, 0, 0.0556, 0.0278, 0, 0.66, 0.25, 516, 0, 1, 0, 0, 516, 0, 0 ], [ 3, 0, 0.3194, 0.3889, 0, 0....
[ "import os", "import tempfile", "class ListenSome:\n \n def __init__(self):\n outpath = os.path.join(tempfile.gettempdir(), 'listen_some.txt')\n self.outfile = open(outpath, 'w')\n \n def startTest(self, name, doc, tags):\n self.outfile.write(name + '\\n')", " def __ini...
import os import tempfile from robot.libraries.BuiltIn import BuiltIn class ListenSome: ROBOT_LISTENER_API_VERSION = '2' def __init__(self): outpath = os.path.join(tempfile.gettempdir(), 'listen_some.txt') self.outfile = open(outpath, 'w') def startTest(self, name, attrs): self.outfile.write(name + '\n') def endSuite(self, name, attrs): self.outfile.write(attrs['statistics'] + '\n') def close(self): self.outfile.close() class WithArgs(object): ROBOT_LISTENER_API_VERSION = '2' def __init__(self, arg1, arg2='default'): outpath = os.path.join(tempfile.gettempdir(), 'listener_with_args.txt') outfile = open(outpath, 'a') outfile.write("I got arguments '%s' and '%s'\n" % (arg1, arg2)) outfile.close() class InvalidMethods: ROBOT_LISTENER_API_VERSION = '2' def start_suite(self, wrong, number, of, args, here): pass def end_suite(self, *args): raise RuntimeError("Here comes an exception!") def message(self, msg): raise ValueError("This fails continuously!") class SuiteAndTestCounts(object): ROBOT_LISTENER_API_VERSION = '2' exp_data = { 'Subsuites & Subsuites2': ([], ['Subsuites', 'Subsuites2'], 4), 'Subsuites': ([], ['Sub1', 'Sub2'], 2), 'Sub1': (['SubSuite1 First'], [], 1), 'Sub2': (['SubSuite2 First'], [], 1), 'Subsuites2': ([], ['Subsuite3'], 2), 'Subsuite3': (['SubSuite3 First', 'SubSuite3 Second'], [], 2), } def start_suite(self, name, attrs): data = attrs['tests'], attrs['suites'], attrs['totaltests'] if not data == self.exp_data[name]: raise RuntimeError('Wrong tests or suites in %s, %s != %s' % (name, self.exp_data[name], data)) class KeywordType(object): ROBOT_LISTENER_API_VERSION = '2' def start_keyword(self, name, attrs): expected = attrs['args'][0] if name == 'BuiltIn.Log' else name if attrs['type'] != expected: raise RuntimeError("Wrong keyword type '%s', expected '%s'." % (attrs['type'], expected)) end_keyword = start_keyword class KeywordExecutingListener(object): ROBOT_LISTENER_API_VERSION = '2' def start_suite(self, name, attrs): self._start(name) def end_suite(self, name, attrs): self._end(name) def start_test(self, name, attrs): self._start(name) def end_test(self, name, attrs): self._end(name) def _start(self, name): self._run_keyword('Start %s' % name) def _end(self, name): self._run_keyword('End %s' % name) def _run_keyword(self, arg): BuiltIn().run_keyword('Log', arg)
[ [ 1, 0, 0.0101, 0.0101, 0, 0.66, 0, 688, 0, 1, 0, 0, 688, 0, 0 ], [ 1, 0, 0.0202, 0.0101, 0, 0.66, 0.125, 516, 0, 1, 0, 0, 516, 0, 0 ], [ 1, 0, 0.0404, 0.0101, 0, 0...
[ "import os", "import tempfile", "from robot.libraries.BuiltIn import BuiltIn", "class ListenSome:\n ROBOT_LISTENER_API_VERSION = '2'\n\n def __init__(self):\n outpath = os.path.join(tempfile.gettempdir(), 'listen_some.txt')\n self.outfile = open(outpath, 'w')\n\n def startTest(self, nam...
import os import tempfile outpath = os.path.join(tempfile.gettempdir(), 'listen_by_module.txt') OUTFILE = open(outpath, 'w') def start_suite(name, doc): OUTFILE.write("SUITE START: %s '%s'\n" % (name, doc)) def start_test(name, doc, tags): tags = [ str(tag) for tag in tags ] OUTFILE.write("TEST START: %s '%s' %s\n" % (name, doc, tags)) def start_keyword(name, args): args = [str(arg) for arg in args] OUTFILE.write("KW START: %s %s\n" % (name, args)) def end_keyword(status): OUTFILE.write("KW END: %s\n" % (status)) def end_test(status, message): if status == 'PASS': OUTFILE.write('TEST END: PASS\n') else: OUTFILE.write("TEST END: %s %s\n" % (status, message)) def end_suite(status, message): OUTFILE.write('SUITE END: %s %s\n' % (status, message)) def output_file(path): _out_file('Output', path) def report_file(path): _out_file('Report', path) def log_file(path): _out_file('Log', path) def debug_file(path): _out_file('Debug', path) def _out_file(name, path): assert os.path.isabs(path) OUTFILE.write('%s: %s\n' % (name, os.path.basename(path))) def close(): OUTFILE.write('Closing...\n') OUTFILE.close()
[ [ 1, 0, 0.0204, 0.0204, 0, 0.66, 0, 688, 0, 1, 0, 0, 688, 0, 0 ], [ 1, 0, 0.0408, 0.0204, 0, 0.66, 0.0667, 516, 0, 1, 0, 0, 516, 0, 0 ], [ 14, 0, 0.0816, 0.0204, 0, ...
[ "import os", "import tempfile", "outpath = os.path.join(tempfile.gettempdir(), 'listen_by_module.txt')", "OUTFILE = open(outpath, 'w')", "def start_suite(name, doc):\n OUTFILE.write(\"SUITE START: %s '%s'\\n\" % (name, doc))", " OUTFILE.write(\"SUITE START: %s '%s'\\n\" % (name, doc))", "def start...
import os import tempfile ROBOT_LISTENER_API_VERSION = '2' OUTFILE = open(os.path.join(tempfile.gettempdir(), 'listener_attrs.txt'), 'w') START_ATTRIBUTES = ['doc', 'starttime'] END_ATTRIBUTES = START_ATTRIBUTES + ['endtime', 'elapsedtime', 'status'] EXPECTED_TYPES = {'elapsedtime': (int, long), 'tags': list, 'args': list, 'metadata': dict, 'tests': list, 'suites': list, 'totaltests': int} def start_suite(name, attrs): _verify_attributes('START SUITE', attrs, START_ATTRIBUTES+['longname', 'metadata', 'tests', 'suites', 'totaltests']) def end_suite(name, attrs): _verify_attributes('END SUITE', attrs, END_ATTRIBUTES+['longname', 'statistics', 'message']) def start_test(name, attrs): _verify_attributes('START TEST', attrs, START_ATTRIBUTES + ['longname', 'tags']) def end_test(name, attrs): _verify_attributes('END TEST', attrs, END_ATTRIBUTES + ['longname', 'tags', 'message']) def start_keyword(name, attrs): _verify_attributes('START KEYWORD', attrs, START_ATTRIBUTES + ['args', 'type']) def end_keyword(name, attrs): _verify_attributes('END KEYWORD', attrs, END_ATTRIBUTES + ['args', 'type']) def _verify_attributes(method_name, attrs, names): OUTFILE.write(method_name + '\n') if len(names) != len(attrs): OUTFILE.write('FAILED: wrong number of attributes\n') OUTFILE.write('Expected: %s\nActual: %s\n' % (names, attrs.keys())) return for name in names: value = attrs[name] exp_type = EXPECTED_TYPES.get(name, basestring) if isinstance(value, exp_type): OUTFILE.write('PASSED | %s: %s\n' % (name, value)) else: OUTFILE.write('FAILED | %s: %r, Expected: %s, Actual: %s\n' % (name, value, type(value), exp_type)) def close(): OUTFILE.close()
[ [ 1, 0, 0.0192, 0.0192, 0, 0.66, 0, 688, 0, 1, 0, 0, 688, 0, 0 ], [ 1, 0, 0.0385, 0.0192, 0, 0.66, 0.0714, 516, 0, 1, 0, 0, 516, 0, 0 ], [ 14, 0, 0.0962, 0.0192, 0, ...
[ "import os", "import tempfile", "ROBOT_LISTENER_API_VERSION = '2'", "OUTFILE = open(os.path.join(tempfile.gettempdir(), 'listener_attrs.txt'), 'w')", "START_ATTRIBUTES = ['doc', 'starttime']", "END_ATTRIBUTES = START_ATTRIBUTES + ['endtime', 'elapsedtime', 'status']", "EXPECTED_TYPES = {'elapsedtime': (...
def get_variables(*args): return { 'PPATH_VARFILE_2' : ' '.join(args), 'LIST__PPATH_VARFILE_2' : args }
[ [ 2, 0, 0.5, 0.75, 0, 0.66, 0, 461, 0, 1, 1, 0, 0, 0, 1 ], [ 13, 1, 0.625, 0.5, 1, 0.13, 0, 0, 0, 0, 0, 0, 0, 6, 1 ] ]
[ "def get_variables(*args):\n return { 'PPATH_VARFILE_2' : ' '.join(args),\n 'LIST__PPATH_VARFILE_2' : args }", " return { 'PPATH_VARFILE_2' : ' '.join(args),\n 'LIST__PPATH_VARFILE_2' : args }" ]
PPATH_VARFILE = "Variable from varible file in PYTHONPATH"
[ [ 14, 0, 1, 1, 0, 0.66, 0, 799, 1, 0, 0, 0, 0, 3, 0 ] ]
[ "PPATH_VARFILE = \"Variable from varible file in PYTHONPATH\"" ]
list1 = [1, 2, 3, 4, 'foo', 'bar'] dictionary1 = {'a': 1} dictionary2 = {'a': 1, 'b': 2}
[ [ 14, 0, 0.3333, 0.3333, 0, 0.66, 0, 150, 0, 0, 0, 0, 0, 5, 0 ], [ 14, 0, 0.6667, 0.3333, 0, 0.66, 0.5, 355, 0, 0, 0, 0, 0, 6, 0 ], [ 14, 0, 1, 0.3333, 0, 0.66, ...
[ "list1 = [1, 2, 3, 4, 'foo', 'bar']", "dictionary1 = {'a': 1}", "dictionary2 = {'a': 1, 'b': 2}" ]
class TraceLogArgsLibrary(object): def only_mandatory(self, mand1, mand2): pass def mandatory_and_default(self, mand, default="default value"): pass def multiple_default_values(self, a=1, a2=2, a3=3, a4=4): pass def mandatory_and_varargs(self, mand, *varargs): pass def return_object_with_invalid_repr(self): return InvalidRepr() def return_object_with_non_ascii_string_repr(self): return ByteRepr() class InvalidRepr: def __repr__(self): return u'Hyv\xe4' class ByteRepr: def __repr__(self): return 'Hyv\xe4'
[ [ 3, 0, 0.3333, 0.6333, 0, 0.66, 0, 552, 0, 6, 0, 0, 186, 0, 2 ], [ 2, 1, 0.1167, 0.0667, 1, 0.83, 0, 124, 0, 3, 0, 0, 0, 0, 0 ], [ 2, 1, 0.2167, 0.0667, 1, 0.83, ...
[ "class TraceLogArgsLibrary(object):\n\n def only_mandatory(self, mand1, mand2):\n pass\n\n def mandatory_and_default(self, mand, default=\"default value\"):\n pass", " def only_mandatory(self, mand1, mand2):\n pass", " def mandatory_and_default(self, mand, default=\"default valu...
class FailUntilSucceeds: ROBOT_LIBRARY_SCOPE = 'TESTCASE' def __init__(self, times_to_fail=0): self.times_to_fail = int(times_to_fail) def fail_until_retried_often_enough(self, message="Hello"): self.times_to_fail -= 1 if self.times_to_fail >= 0: raise Exception('Still %d times to fail!' % (self.times_to_fail)) return message
[ [ 3, 0, 0.5417, 1, 0, 0.66, 0, 243, 0, 2, 0, 0, 0, 0, 2 ], [ 14, 1, 0.25, 0.0833, 1, 0.59, 0, 305, 1, 0, 0, 0, 0, 3, 0 ], [ 2, 1, 0.4583, 0.1667, 1, 0.59, 0.5, ...
[ "class FailUntilSucceeds:\n \n ROBOT_LIBRARY_SCOPE = 'TESTCASE'\n \n def __init__(self, times_to_fail=0):\n self.times_to_fail = int(times_to_fail)\n \n def fail_until_retried_often_enough(self, message=\"Hello\"):", " ROBOT_LIBRARY_SCOPE = 'TESTCASE'", " def __init__(self, times_...
import exceptions class ObjectToReturn: def __init__(self, name): self.name = name def __str__(self): return self.name def exception(self, name, msg=""): exception = getattr(exceptions, name) raise exception, msg
[ [ 1, 0, 0.0833, 0.0833, 0, 0.66, 0, 63, 0, 1, 0, 0, 63, 0, 0 ], [ 3, 0, 0.625, 0.8333, 0, 0.66, 1, 601, 0, 3, 0, 0, 0, 0, 1 ], [ 2, 1, 0.4583, 0.1667, 1, 0.08, ...
[ "import exceptions", "class ObjectToReturn:\n \n def __init__(self, name):\n self.name = name\n\n def __str__(self):\n return self.name", " def __init__(self, name):\n self.name = name", " self.name = name", " def __str__(self):\n return self.name", " ...
class SameNamesAsInBuiltIn: def noop(self): """Using this keyword without libname causes an error"""
[ [ 3, 0, 0.625, 1, 0, 0.66, 0, 82, 0, 1, 0, 0, 0, 0, 0 ], [ 2, 1, 0.875, 0.5, 1, 0.15, 0, 907, 0, 1, 0, 0, 0, 0, 0 ], [ 8, 2, 1, 0.25, 2, 0.89, 0, 0, 1, ...
[ "class SameNamesAsInBuiltIn:\n \n def noop(self):\n \"\"\"Using this keyword without libname causes an error\"\"\"", " def noop(self):\n \"\"\"Using this keyword without libname causes an error\"\"\"", " \"\"\"Using this keyword without libname causes an error\"\"\"" ]
class ZipLib: def kw_from_zip(self, arg): print '*INFO*', arg return arg * 2
[ [ 3, 0, 0.4286, 0.7143, 0, 0.66, 0, 240, 0, 1, 0, 0, 0, 0, 1 ], [ 2, 1, 0.5714, 0.4286, 1, 0.86, 0, 374, 0, 2, 1, 0, 0, 0, 1 ], [ 8, 2, 0.5714, 0.1429, 2, 0.85, ...
[ "class ZipLib:\n\n\tdef kw_from_zip(self, arg):\n\t\tprint('*INFO*', arg)\n\t\treturn arg * 2", "\tdef kw_from_zip(self, arg):\n\t\tprint('*INFO*', arg)\n\t\treturn arg * 2", "\t\tprint('*INFO*', arg)", "\t\treturn arg * 2" ]
class PythonVarArgsConstructor: def __init__(self, mandatory, *varargs): self.mandatory = mandatory self.varargs = varargs def get_args(self): return self.mandatory, ' '.join(self.varargs)
[ [ 3, 0, 0.5, 0.8889, 0, 0.66, 0, 282, 0, 2, 0, 0, 0, 0, 1 ], [ 2, 1, 0.4444, 0.3333, 1, 0.52, 0, 555, 0, 3, 0, 0, 0, 0, 0 ], [ 14, 2, 0.4444, 0.1111, 2, 0.45, 0...
[ "class PythonVarArgsConstructor:\n \n def __init__(self, mandatory, *varargs):\n self.mandatory = mandatory\n self.varargs = varargs\n\n def get_args(self):\n return self.mandatory, ' '.join(self.varargs)", " def __init__(self, mandatory, *varargs):\n self.mandatory = manda...
import ExampleJavaLibrary import DefaultArgs class ExtendJavaLib(ExampleJavaLibrary): def kw_in_java_extender(self, arg): return arg*2 def javaSleep(self, secs): raise Exception('Overridden kw executed!') def using_method_from_java_parent(self): self.divByZero() class ExtendJavaLibWithConstructor(DefaultArgs): def keyword(self): return None class ExtendJavaLibWithInit(ExampleJavaLibrary): def __init__(self, *args): self.args = args def get_args(self): return self.args class ExtendJavaLibWithInitAndConstructor(DefaultArgs): def __init__(self, *args): if len(args) == 1: DefaultArgs.__init__(self, args[0]) self.kw = lambda self: "Hello, world!"
[ [ 1, 0, 0.027, 0.027, 0, 0.66, 0, 716, 0, 1, 0, 0, 716, 0, 0 ], [ 1, 0, 0.0541, 0.027, 0, 0.66, 0.2, 96, 0, 1, 0, 0, 96, 0, 0 ], [ 3, 0, 0.2568, 0.2703, 0, 0.66, ...
[ "import ExampleJavaLibrary", "import DefaultArgs", "class ExtendJavaLib(ExampleJavaLibrary):\n\n def kw_in_java_extender(self, arg):\n return arg*2\n\n def javaSleep(self, secs):\n raise Exception('Overridden kw executed!')", " def kw_in_java_extender(self, arg):\n return arg*2",...
class ArgumentsPython: # method docs are used in unit tests as expected min and max args def a_0(self): """(0,0)""" return 'a_0' def a_1(self, arg): """(1,1)""" return 'a_1: ' + arg def a_3(self, arg1, arg2, arg3): """(3,3)""" return ' '.join(['a_3:',arg1,arg2,arg3]) def a_0_1(self, arg='default'): """(0,1)""" return 'a_0_1: ' + arg def a_1_3(self, arg1, arg2='default', arg3='default'): """(1,3)""" return ' '.join(['a_1_3:',arg1,arg2,arg3]) def a_0_n(self, *args): """(0,sys.maxint)""" return ' '.join(['a_0_n:', ' '.join(args)]) def a_1_n(self, arg, *args): """(1,sys.maxint)""" return ' '.join(['a_1_n:', arg, ' '.join(args)]) def a_1_2_n(self, arg1, arg2='default', *args): """(1,sys.maxint)""" return ' '.join(['a_1_2_n:', arg1, arg2, ' '.join(args)])
[ [ 3, 0, 0.5, 0.9722, 0, 0.66, 0, 360, 0, 8, 0, 0, 0, 0, 8 ], [ 2, 1, 0.1667, 0.0833, 1, 0.33, 0, 653, 0, 1, 1, 0, 0, 0, 0 ], [ 8, 2, 0.1667, 0.0278, 2, 0.28, 0,...
[ "class ArgumentsPython:\n \n # method docs are used in unit tests as expected min and max args\n \n def a_0(self):\n \"\"\"(0,0)\"\"\"\n return 'a_0'", " def a_0(self):\n \"\"\"(0,0)\"\"\"\n return 'a_0'", " \"\"\"(0,0)\"\"\"", " return 'a_0'", " d...
from robot import utils class RunKeywordLibrary: ROBOT_LIBRARY_SCOPE = 'TESTCASE' def __init__(self): self.kw_names = ['Run Keyword That Passes', 'Run Keyword That Fails'] def get_keyword_names(self): return self.kw_names def run_keyword(self, name, args): try: method = dict(zip(self.kw_names, [self._passes, self._fails]))[name] except KeyError: raise AttributeError return method(args) def _passes(self, args): for arg in args: print arg, return ', '.join(args) def _fails(self, args): if not args: raise AssertionError('Failure') raise AssertionError('Failure: %s' % ' '.join(args)) class GlobalRunKeywordLibrary(RunKeywordLibrary): ROBOT_LIBRARY_SCOPE = 'GLOBAL' class RunKeywordButNoGetKeywordNamesLibrary: def run_keyword(self, *args): return ' '.join(args) def some_other_keyword(self, *args): return ' '.join(args)
[ [ 1, 0, 0.0244, 0.0244, 0, 0.66, 0, 735, 0, 1, 0, 0, 735, 0, 0 ], [ 3, 0, 0.3902, 0.6098, 0, 0.66, 0.3333, 741, 0, 5, 0, 0, 0, 0, 8 ], [ 14, 1, 0.122, 0.0244, 1, 0....
[ "from robot import utils", "class RunKeywordLibrary:\n ROBOT_LIBRARY_SCOPE = 'TESTCASE'\n\n def __init__(self):\n self.kw_names = ['Run Keyword That Passes', 'Run Keyword That Fails']\n\n def get_keyword_names(self):\n return self.kw_names", " ROBOT_LIBRARY_SCOPE = 'TESTCASE'", " ...
library = "It should be OK to have an attribute with same name as the module" def keyword_from_submodule(arg='World'): return "Hello, %s!" % arg
[ [ 14, 0, 0.2, 0.2, 0, 0.66, 0, 860, 1, 0, 0, 0, 0, 3, 0 ], [ 2, 0, 0.9, 0.4, 0, 0.66, 1, 962, 0, 1, 1, 0, 0, 0, 0 ], [ 13, 1, 1, 0.2, 1, 0.83, 0, 0, 4, ...
[ "library = \"It should be OK to have an attribute with same name as the module\"", "def keyword_from_submodule(arg='World'):\n return \"Hello, %s!\" % arg", " return \"Hello, %s!\" % arg" ]
some_string = 'Hello, World!' class _SomeObject: pass some_object = _SomeObject()
[ [ 14, 0, 0.1667, 0.1667, 0, 0.66, 0, 913, 1, 0, 0, 0, 0, 3, 0 ], [ 3, 0, 0.5833, 0.3333, 0, 0.66, 0.5, 122, 0, 0, 0, 0, 0, 0, 0 ], [ 14, 0, 1, 0.1667, 0, 0.66, ...
[ "some_string = 'Hello, World!'", "class _SomeObject:\n pass", "some_object = _SomeObject()" ]
class KwargsLibrary(object): def __init__(self, arg1=None, arg2=None): self.arg1 = arg1 self.arg2 = arg2 def check_init_arguments(self, exp_arg1, exp_arg2): if self.arg1 != exp_arg1 or self.arg2 != exp_arg2: raise AssertionError('Wrong initialization values. Got (%s, %s), expected (%s, %s)' % (self.arg1, self.arg2, exp_arg1, exp_arg2)) def one_kwarg(self, kwarg=None): return kwarg def two_kwargs(self, fst=None, snd=None): return '%s, %s' % (fst, snd) def four_kwargs(self, a=None, b=None, c=None, d=None): return '%s, %s, %s, %s' % (a, b, c, d) def mandatory_and_kwargs(self, a, b, c=None): return '%s, %s, %s' % (a, b, c) def kwargs_and_mandatory_args(self, mandatory, d1=None, d2=None, *varargs): return '%s, %s, %s, %s' % (mandatory, d1, d2, '[%s]' % ', '.join(varargs))
[ [ 3, 0, 0.52, 1, 0, 0.66, 0, 328, 0, 7, 0, 0, 186, 0, 2 ], [ 2, 1, 0.16, 0.12, 1, 0.16, 0, 555, 0, 3, 0, 0, 0, 0, 0 ], [ 14, 2, 0.16, 0.04, 2, 0.2, 0, 572, ...
[ "class KwargsLibrary(object):\n\n def __init__(self, arg1=None, arg2=None):\n self.arg1 = arg1\n self.arg2 = arg2\n\n def check_init_arguments(self, exp_arg1, exp_arg2):\n if self.arg1 != exp_arg1 or self.arg2 != exp_arg2:", " def __init__(self, arg1=None, arg2=None):\n self.a...
class ParameterLibrary: def __init__(self, host='localhost', port='8080'): self.host = host self.port = port def parameters(self): return self.host, self.port
[ [ 3, 0, 0.5625, 1, 0, 0.66, 0, 341, 0, 2, 0, 0, 0, 0, 0 ], [ 2, 1, 0.5, 0.375, 1, 0.76, 0, 555, 0, 3, 0, 0, 0, 0, 0 ], [ 14, 2, 0.5, 0.125, 2, 0.08, 0, 445,...
[ "class ParameterLibrary:\n \n def __init__(self, host='localhost', port='8080'):\n self.host = host\n self.port = port\n \n def parameters(self):\n return self.host, self.port", " def __init__(self, host='localhost', port='8080'):\n self.host = host\n self.por...
from robot import utils def passing_handler(*args): for arg in args: print arg, return ', '.join(args) def failing_handler(*args): if len(args) == 0: msg = 'Failure' else: msg = 'Failure: %s' % ' '.join(args) raise AssertionError(msg) class GetKeywordNamesLibrary: def __init__(self): self.this_is_not_keyword = 'This is just an attribute!!' def get_keyword_names(self): return ['Get Keyword That Passes', 'Get Keyword That Fails', 'keyword_in_library_itself', 'non_existing_kw', 'this_is_not_keyword'] def __getattr__(self, name): if name == 'Get Keyword That Passes': return passing_handler if name == 'Get Keyword That Fails': return failing_handler raise AttributeError("Non-existing keyword '%s'" % name) def keyword_in_library_itself(self): msg = 'No need for __getattr__ here!!' print msg return msg
[ [ 1, 0, 0.027, 0.027, 0, 0.66, 0, 735, 0, 1, 0, 0, 735, 0, 0 ], [ 2, 0, 0.1486, 0.1081, 0, 0.66, 0.3333, 44, 0, 1, 1, 0, 0, 0, 2 ], [ 6, 1, 0.1486, 0.0541, 1, 0.27,...
[ "from robot import utils", "def passing_handler(*args):\n for arg in args:\n print(arg,)\n return ', '.join(args)", " for arg in args:\n print(arg,)", " print(arg,)", " return ', '.join(args)", "def failing_handler(*args):\n if len(args) == 0:\n msg = 'Failure'\n...
class Mandatory: def __init__(self, mandatory1, mandatory2): self.mandatory1 = mandatory1 self.mandatory2 = mandatory2 def get_args(self): return self.mandatory1, self.mandatory2 class Defaults(object): def __init__(self, mandatory, default1='value', default2=None): self.mandatory = mandatory self.default1 = default1 self.default2 = default2 def get_args(self): return self.mandatory, self.default1, self.default2 class Varargs(Mandatory): def __init__(self, mandatory, *varargs): Mandatory.__init__(self, mandatory, ' '.join(str(a) for a in varargs)) class Mixed(Defaults): def __init__(self, mandatory, default=42, *extra): Defaults.__init__(self, mandatory, default, ' '.join(str(a) for a in extra))
[ [ 3, 0, 0.1406, 0.25, 0, 0.66, 0, 745, 0, 2, 0, 0, 0, 0, 0 ], [ 2, 1, 0.125, 0.0938, 1, 0.67, 0, 555, 0, 3, 0, 0, 0, 0, 0 ], [ 14, 2, 0.125, 0.0312, 2, 0.12, 0,...
[ "class Mandatory:\n\n def __init__(self, mandatory1, mandatory2):\n self.mandatory1 = mandatory1\n self.mandatory2 = mandatory2\n\n def get_args(self):\n return self.mandatory1, self.mandatory2", " def __init__(self, mandatory1, mandatory2):\n self.mandatory1 = mandatory1\n ...
from ExampleLibrary import ExampleLibrary class ExtendPythonLib(ExampleLibrary): def kw_in_python_extender(self, arg): return arg/2 def print_many(self, *msgs): raise Exception('Overridden kw executed!') def using_method_from_python_parent(self): self.exception('AssertionError', 'Error message from lib')
[ [ 1, 0, 0.0833, 0.0833, 0, 0.66, 0, 472, 0, 1, 0, 0, 472, 0, 0 ], [ 3, 0, 0.625, 0.8333, 0, 0.66, 1, 677, 0, 3, 0, 0, 472, 0, 2 ], [ 2, 1, 0.4583, 0.1667, 1, 0.02, ...
[ "from ExampleLibrary import ExampleLibrary", "class ExtendPythonLib(ExampleLibrary):\n \n def kw_in_python_extender(self, arg):\n return arg/2\n \n def print_many(self, *msgs):\n raise Exception('Overridden kw executed!')", " def kw_in_python_extender(self, arg):\n return arg...
__version__ = 'N/A' # This should be ignored when version is parsed class NameLibrary: handler_count = 10 def simple1(self): """Simple 1""" def simple2___(self): """Simple 2""" def underscore_name(self): """Underscore Name""" def underscore_name2_(self): """Underscore Name2""" def un_der__sco_r__e_3(self): """Un Der Sco R E 3""" def MiXeD_CAPS(self): """MiXeD CAPS""" def camelCase(self): """Camel Case""" def camelCase2(self): """Camel Case 2""" def mixedCAPSCamel(self): """Mixed CAPS Camel""" def camelCase_and_underscores_doesNot_work(self): """CamelCase And Underscores DoesNot Work""" def _skipped1(self): """Starts with underscore""" skipped2 = "Not a function" class DocLibrary: handler_count = 3 def no_doc(self): pass no_doc.expected_doc = '' no_doc.expected_shortdoc = '' def one_line_doc(self): """One line doc""" one_line_doc.expected_doc = 'One line doc' one_line_doc.expected_shortdoc = 'One line doc' def multiline_doc(self): """Multiline doc. Spans multiple lines. """ multiline_doc.expected_doc = 'Multiline doc.\n\nSpans multiple lines.' multiline_doc.expected_shortdoc = 'Multiline doc.' class ArgInfoLibrary: handler_count = 11 def no_args(self): """[], [], None""" # Argument inspection had a bug when there was args on function body # so better keep some of them around here. a=b=c=1 def required1(self, one): """['one',], [], None""" def required2(self, one, two): """['one','two'], [], None""" def required9(self, one, two, three, four, five, six, seven, eight, nine): """['one','two','three','four','five','six','seven','eight','nine'],\ [], None""" def default1(self, one=1): """['one'], [1], None""" def default5(self, one='', two=None, three=3, four='huh', five=True): """['one','two','three','four','five'], ['',None,3,'huh',True], None""" def required1_default1(self, one, two=''): """['one','two'], [''], None""" def required2_default3(self, one, two, three=3, four=4, five=5): """['one','two','three','four','five'], [3,4,5], None""" def varargs(self,*one): """[], [], 'one'""" def required2_varargs(self, one, two, *three): """['one','two'], [], 'three'""" def req4_def2_varargs(self, one, two, three, four, five=5, six=6, *seven): """['one','two','three','four','five','six'], [5,6], 'seven'""" class GetattrLibrary: handler_count = 3 keyword_names = ['foo','bar','zap'] def get_keyword_names(self): return self.keyword_names def __getattr__(self, name): def handler(*args): return name, args if name not in self.keyword_names: raise AttributeError return handler class SynonymLibrary: handler_count = 3 def handler(self): pass synonym_handler = handler another_synonym = handler class VersionLibrary: ROBOT_LIBRARY_VERSION = '0.1' kw = lambda x:None class VersionObjectLibrary: class _Version: def __init__(self, ver): self._ver = ver def __str__(self): return self._ver ROBOT_LIBRARY_VERSION = _Version('ver') kw = lambda x:None class RecordingLibrary: ROBOT_LIBRARY_SCOPE = 'GLOBAL' def __init__(self): self.calls_to_getattr = 0 def kw(self): pass def __getattr__(self, name): self.calls_to_getattr += 1 if name != 'kw': raise AttributeError return self.kw class ArgDocDynamicLibrary: def __init__(self): kws = [('No Arg', []), ('One Arg', ['arg']), ('One or Two Args', ['arg', 'darg=dvalue']), ('Many Args', ['*args'])] self._keywords = dict((name, _KeywordInfo(name, argspec)) for name, argspec in kws) def get_keyword_names(self): return sorted(self._keywords.keys()) def run_keyword(self, name, *args): print '*INFO* Executed keyword %s with arguments %s' % (name, args) def get_keyword_documentation(self, name): return self._keywords[name].doc def get_keyword_arguments(self, name): return self._keywords[name].argspec class _KeywordInfo: doc_template = 'Keyword documentation for %s' def __init__(self, name, argspec): self.doc = self.doc_template % name self.argspec = argspec class InvalidGetDocDynamicLibrary(ArgDocDynamicLibrary): def get_keyword_documentation(self, name, invalid_arg): pass class InvalidGetArgsDynamicLibrary(ArgDocDynamicLibrary): def get_keyword_arguments(self, name): 1/0 class InvalidAttributeDynamicLibrary(ArgDocDynamicLibrary): get_keyword_documentation = True get_keyword_arguments = False
[ [ 14, 0, 0.0061, 0.0061, 0, 0.66, 0, 162, 1, 0, 0, 0, 0, 3, 0 ], [ 3, 0, 0.0982, 0.1534, 0, 0.66, 0.0769, 353, 0, 11, 0, 0, 0, 0, 0 ], [ 14, 1, 0.0307, 0.0061, 1, 0...
[ "__version__ = 'N/A' # This should be ignored when version is parsed", "class NameLibrary:\n handler_count = 10\n def simple1(self):\n \"\"\"Simple 1\"\"\"\n def simple2___(self):\n \"\"\"Simple 2\"\"\"\n def underscore_name(self):\n \"\"\"Underscore Name\"\"\"", " handler_c...
class NewStyleClassLibrary(object): def mirror(self, arg): arg = list(arg) arg.reverse() return ''.join(arg) def _property_getter(self): raise SystemExit('This should not be called, ever!!!') prop = property(_property_getter) class NewStyleClassArgsLibrary(object): def __init__(self, param): self.get_param = lambda self: param class _MyMetaClass(type): def __new__(cls, name, bases, ns): ns['kw_created_by_metaclass'] = lambda self, arg: arg.upper() return type.__new__(cls, name, bases, ns) def method_in_metaclass(cls): pass class MetaClassLibrary(object): __metaclass__ = _MyMetaClass def greet(self, name): return 'Hello %s!' % name
[ [ 3, 0, 0.1765, 0.3235, 0, 0.66, 0, 12, 0, 2, 0, 0, 186, 0, 5 ], [ 2, 1, 0.1324, 0.1176, 1, 0.54, 0, 697, 0, 2, 1, 0, 0, 0, 3 ], [ 14, 2, 0.1176, 0.0294, 2, 0.31, ...
[ "class NewStyleClassLibrary(object):\n \n def mirror(self, arg):\n arg = list(arg)\n arg.reverse()\n return ''.join(arg)\n\n def _property_getter(self):", " def mirror(self, arg):\n arg = list(arg)\n arg.reverse()\n return ''.join(arg)", " arg = list(...
class LibClass1: def verify_libclass1(self): return 'LibClass 1 works' class LibClass2: def verify_libclass2(self): return 'LibClass 2 works also'
[ [ 3, 0, 0.2273, 0.3636, 0, 0.66, 0, 529, 0, 1, 0, 0, 0, 0, 0 ], [ 2, 1, 0.3182, 0.1818, 1, 0.82, 0, 99, 0, 1, 1, 0, 0, 0, 0 ], [ 13, 2, 0.3636, 0.0909, 2, 0.32, ...
[ "class LibClass1:\n \n def verify_libclass1(self):\n return 'LibClass 1 works'", " def verify_libclass1(self):\n return 'LibClass 1 works'", " return 'LibClass 1 works'", "class LibClass2:\n\n def verify_libclass2(self):\n return 'LibClass 2 works also'", " def ver...
class FatalCatastrophyException(RuntimeError): ROBOT_EXIT_ON_FAILURE = True class ContinuableApocalypseException(RuntimeError): ROBOT_CONTINUE_ON_FAILURE = True def exit_on_failure(): raise FatalCatastrophyException() def raise_continuable_failure(msg='Can be continued'): raise ContinuableApocalypseException(msg)
[ [ 3, 0, 0.1364, 0.1818, 0, 0.66, 0, 572, 0, 0, 0, 0, 178, 0, 0 ], [ 14, 1, 0.1818, 0.0909, 1, 0.31, 0, 675, 1, 0, 0, 0, 0, 4, 0 ], [ 3, 0, 0.4091, 0.1818, 0, 0.66, ...
[ "class FatalCatastrophyException(RuntimeError):\n ROBOT_EXIT_ON_FAILURE = True", " ROBOT_EXIT_ON_FAILURE = True", "class ContinuableApocalypseException(RuntimeError):\n ROBOT_CONTINUE_ON_FAILURE = True", " ROBOT_CONTINUE_ON_FAILURE = True", "def exit_on_failure():\n raise FatalCatastrophyExce...
ROBOT_LIBRARY_SCOPE = 'Test Suite' # this should be ignored __version__ = 'test' # this should be used as version of this library def passing(): pass def failing(): raise AssertionError('This is a failing keyword from module library') def logging(): print 'Hello from module library' print '*WARN* WARNING!' def returning(): return 'Hello from module library' def argument(arg): assert arg == 'Hello', "Expected 'Hello', got '%s'" % arg def many_arguments(arg1, arg2, arg3): assert arg1 == arg2 == arg3, ("All arguments should have been equal, got: " "%s, %s and %s") % (arg1, arg2, arg3) def default_arguments(arg1, arg2='Hi', arg3='Hello'): many_arguments(arg1, arg2, arg3) def variable_arguments(*args): return sum([int(arg) for arg in args]) attribute = 'This is not a keyword!' class NotLibrary: def two_arguments(self, arg1, arg2): msg = "Arguments should have been unequal, both were '%s'" % arg1 assert arg1 != arg2, msg def not_keyword(self): pass notlib = NotLibrary() two_arguments_from_class = notlib.two_arguments lambda_keyword = lambda arg: int(arg) + 1 lambda_keyword_with_two_args = lambda x, y: int(x) / int(y) def _not_keyword(): pass def module_library(): return "It should be OK to have an attribute with same name as the module"
[ [ 14, 0, 0.0185, 0.0185, 0, 0.66, 0, 305, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.037, 0.0185, 0, 0.66, 0.0588, 162, 1, 0, 0, 0, 0, 3, 0 ], [ 2, 0, 0.1019, 0.037, 0, 0.66...
[ "ROBOT_LIBRARY_SCOPE = 'Test Suite' # this should be ignored", "__version__ = 'test' # this should be used as version of this library", "def passing():\n pass", "def failing():\n raise AssertionError('This is a failing keyword from module library')", "def logging():\n print('Hello from module lib...
import os import re from robot import utils from robot.output import readers from robot.common import Statistics from robot.libraries.BuiltIn import BuiltIn class TestCheckerLibrary: def process_output(self, path): path = path.replace('/', os.sep) try: print "Processing output '%s'" % path suite, errors = readers.process_output(path) except: raise RuntimeError('Processing output failed: %s' % utils.get_error_message()) setter = BuiltIn().set_suite_variable setter('$SUITE', process_suite(suite)) setter('$STATISTICS', Statistics(suite)) setter('$ERRORS', process_errors(errors)) def get_test_from_suite(self, suite, name): tests = self.get_tests_from_suite(suite, name) if len(tests) == 1: return tests[0] elif len(tests) == 0: err = "No test '%s' found from suite '%s'" else: err = "More than one test '%s' found from suite '%s'" raise RuntimeError(err % (name, suite.name)) def get_tests_from_suite(self, suite, name=None): tests = [ test for test in suite.tests if name is None or utils.eq(test.name, name) ] for subsuite in suite.suites: tests.extend(self.get_tests_from_suite(subsuite, name)) return tests def get_suite_from_suite(self, suite, name): suites = self.get_suites_from_suite(suite, name) if len(suites) == 1: return suites[0] elif len(suites) == 0: err = "No suite '%s' found from suite '%s'" else: err = "More than one suite '%s' found from suite '%s'" raise RuntimeError(err % (name, suite.name)) def get_suites_from_suite(self, suite, name): suites = utils.eq(suite.name, name) and [ suite ] or [] for subsuite in suite.suites: suites.extend(self.get_suites_from_suite(subsuite, name)) return suites def check_test_status(self, test, status=None, message=None): """Verifies that test's status and message are as expected. Expected status and message can be given as parameters. If expected status is not given, expected status and message are read from test's documentation. If documentation doesn't contain any of PASS, FAIL or ERROR, test's status is expected to be PASS. If status is given that is used. Expected message is documentation after given status. Expected message can also be regular expression. In that case expected match starts with REGEXP: , which is ignored in the regexp match. """ if status is not None: test.exp_status = status if message is not None: test.exp_message = message if test.exp_status != test.status: if test.exp_status == 'PASS': msg = "Test was expected to PASS but it FAILED. " msg += "Error message:\n" + test.message else: msg = "Test was expected to FAIL but it PASSED. " msg += "Expected message:\n" + test.exp_message raise AssertionError(msg) if test.exp_message == test.message: return if test.exp_message.startswith('REGEXP:'): pattern = test.exp_message.replace('REGEXP:', '', 1).strip() if re.match('^%s$' % pattern, test.message, re.DOTALL): return if test.exp_message.startswith('STARTS:'): start = test.exp_message.replace('STARTS:', '', 1).strip() if start == '': raise RuntimeError("Empty 'STARTS:' is not allowed") if test.message.startswith(start): return raise AssertionError("Wrong message\n\n" "Expected:\n%s\n\nActual:\n%s\n" % (test.exp_message, test.message)) def check_suite_contains_tests(self, suite, *expected_names): actual_tests = [ test for test in self.get_tests_from_suite(suite) ] tests_msg = """ Expected tests : %s Actual tests : %s""" % (str(list(expected_names)), str(actual_tests)) expected_names = [ utils.normalize(name) for name in expected_names ] if len(actual_tests) != len(expected_names): raise AssertionError("Wrong number of tests." + tests_msg) for test in actual_tests: if utils.eq_any(test.name, expected_names): print "Verifying test '%s'" % test.name self.check_test_status(test) expected_names.remove(utils.normalize(test.name)) else: raise AssertionError("Test '%s' was not expected to be run.%s" % (test.name, tests_msg)) if len(expected_names) != 0: raise Exception("Bug in test library") def get_node(self, file_path, node_path=None): dom = utils.DomWrapper(file_path) return dom.get_node(node_path) if node_path else dom def get_nodes(self, file_path, node_path): return utils.DomWrapper(file_path).get_nodes(node_path) def process_suite(suite): for subsuite in suite.suites: process_suite(subsuite) for test in suite.tests: process_test(test) suite.test_count = suite.get_test_count() process_keyword(suite.setup) process_keyword(suite.teardown) return suite def process_test(test): if 'FAIL' in test.doc: test.exp_status = 'FAIL' test.exp_message = test.doc.split('FAIL', 1)[1].lstrip() else: test.exp_status = 'PASS' test.exp_message = '' test.kws = test.keywords test.keyword_count = test.kw_count = len(test.keywords) for kw in test.keywords: process_keyword(kw) process_keyword(test.setup) process_keyword(test.teardown) def process_keyword(kw): if kw is None: return kw.kws = kw.keywords kw.msgs = kw.messages kw.message_count = kw.msg_count = len(kw.messages) kw.keyword_count = kw.kw_count = len(kw.keywords) for subkw in kw.keywords: process_keyword(subkw) def process_errors(errors): errors.msgs = errors.messages errors.message_count = errors.msg_count = len(errors.messages) return errors
[ [ 1, 0, 0.0061, 0.0061, 0, 0.66, 0, 688, 0, 1, 0, 0, 688, 0, 0 ], [ 1, 0, 0.0121, 0.0061, 0, 0.66, 0.1, 540, 0, 1, 0, 0, 540, 0, 0 ], [ 1, 0, 0.0242, 0.0061, 0, 0.6...
[ "import os", "import re", "from robot import utils", "from robot.output import readers", "from robot.common import Statistics", "from robot.libraries.BuiltIn import BuiltIn", "class TestCheckerLibrary:\n\n def process_output(self, path):\n path = path.replace('/', os.sep)\n try:\n ...
import os.path import robot import tempfile __all__ = ['robotpath', 'javatempdir', 'robotversion'] robotpath = os.path.abspath(os.path.dirname(robot.__file__)) javatempdir = tempfile.gettempdir() # Used to be different on OSX and elsewhere robotversion = robot.version.get_version()
[ [ 1, 0, 0.1111, 0.1111, 0, 0.66, 0, 79, 0, 1, 0, 0, 79, 0, 0 ], [ 1, 0, 0.2222, 0.1111, 0, 0.66, 0.1667, 735, 0, 1, 0, 0, 735, 0, 0 ], [ 1, 0, 0.3333, 0.1111, 0, 0....
[ "import os.path", "import robot", "import tempfile", "__all__ = ['robotpath', 'javatempdir', 'robotversion']", "robotpath = os.path.abspath(os.path.dirname(robot.__file__))", "javatempdir = tempfile.gettempdir() # Used to be different on OSX and elsewhere", "robotversion = robot.version.get_version()" ]
message_list = [ u'Circle is 360\u00B0', u'Hyv\u00E4\u00E4 \u00FC\u00F6t\u00E4', u'\u0989\u09C4 \u09F0 \u09FA \u099F \u09EB \u09EA \u09B9' ] message1 = message_list[0] message2 = message_list[1] message3 = message_list[2] messages = ', '.join(message_list) sect = unichr(167) auml = unichr(228) ouml = unichr(246) uuml = unichr(252) yuml = unichr(255)
[ [ 14, 0, 0.1333, 0.2, 0, 0.66, 0, 656, 0, 0, 0, 0, 0, 5, 0 ], [ 14, 0, 0.3333, 0.0667, 0, 0.66, 0.1111, 880, 6, 0, 0, 0, 0, 0, 0 ], [ 14, 0, 0.4, 0.0667, 0, 0.66, ...
[ "message_list = [ u'Circle is 360\\u00B0',\n u'Hyv\\u00E4\\u00E4 \\u00FC\\u00F6t\\u00E4',\n u'\\u0989\\u09C4 \\u09F0 \\u09FA \\u099F \\u09EB \\u09EA \\u09B9' ]", "message1 = message_list[0]", "message2 = message_list[1]", "message3 = message_list[2]", "messages = ', '.join(messag...
from xml.dom.minidom import parse def parse_xunit(path): return parse(path) def get_root_element_name(dom): return dom.documentElement.tagName def get_element_count_by_name(dom, name): return len(get_elements_by_name(dom, name)) def get_elements_by_name(dom, name): return dom.getElementsByTagName(name)
[ [ 1, 0, 0.0769, 0.0769, 0, 0.66, 0, 770, 0, 1, 0, 0, 770, 0, 0 ], [ 2, 0, 0.2692, 0.1538, 0, 0.66, 0.25, 889, 0, 1, 1, 0, 0, 0, 1 ], [ 13, 1, 0.3077, 0.0769, 1, 0.3...
[ "from xml.dom.minidom import parse", "def parse_xunit(path):\n return parse(path)", " return parse(path)", "def get_root_element_name(dom):\n return dom.documentElement.tagName", " return dom.documentElement.tagName", "def get_element_count_by_name(dom, name):\n return len(get_elements_by_n...
import os import sys from stat import S_IREAD, S_IWRITE class TestHelper: def set_read_only(self, path): os.chmod(path, S_IREAD) def set_read_write(self, path): os.chmod(path, S_IREAD | S_IWRITE) def get_output_name(self, *datasources): if not datasources: raise RuntimeError('One or more data sources must be given!') if len(datasources) == 1: return self._get_name(datasources[0]) return '_'.join(self._get_name(source) for source in datasources) def _get_name(self, path): return os.path.splitext(os.path.basename(path))[0] def should_contain_item_x_times(self, string, item, count): if string.count(item) != int(count): raise AssertionError("'%s' does not contain '%s' '%s' " "times!" % (string, item, count)) def get_splitted_full_name(self, full_name, splitlevel): splitlevel = int(splitlevel) parts = full_name.split('.') if splitlevel > 0 and splitlevel <= len(parts): parts = parts[splitlevel:] return '.'.join(parts) def running_on_jython(self, interpreter): return 'jython' in interpreter def running_on_python(self, interpreter): return not self.running_on_jython(interpreter) def running_on_linux(self): return 'linux' in sys.platform
[ [ 1, 0, 0.0233, 0.0233, 0, 0.66, 0, 688, 0, 1, 0, 0, 688, 0, 0 ], [ 1, 0, 0.0465, 0.0233, 0, 0.66, 0.3333, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.0698, 0.0233, 0, ...
[ "import os", "import sys", "from stat import S_IREAD, S_IWRITE", "class TestHelper:\n \n def set_read_only(self, path):\n os.chmod(path, S_IREAD)\n\n def set_read_write(self, path):\n os.chmod(path, S_IREAD | S_IWRITE)", " def set_read_only(self, path):\n os.chmod(path, S_IR...
#!/usr/bin/env python """Script to generate atest runners based on data files. Usage: %s path/to/data.file """ from __future__ import with_statement import sys, os if len(sys.argv) != 2: print __doc__ % os.path.basename(sys.argv[0]) sys.exit(1) inpath = os.path.abspath(sys.argv[1]) outpath = inpath.replace(os.path.join('atest', 'testdata'), os.path.join('atest', 'robot')) dirname = os.path.dirname(outpath) if not os.path.exists(dirname): os.mkdir(dirname) with open(inpath) as input: tests = [] process = False for line in input.readlines(): line = line.rstrip() if line.startswith('*'): name = line.replace('*', '').replace(' ', '').upper() process = name in ('TESTCASE', 'TESTCASES') elif process and line and line[0] != ' ': tests.append(line.split(' ')[0]) with open(outpath, 'w') as output: path = inpath.split(os.path.join('atest', 'testdata'))[1][1:] output.write("""*** Settings *** Suite Setup Run Tests ${EMPTY} %s Force Tags regression pybot jybot Resource atest_resource.txt *** Test Cases *** """ % path.replace(os.sep, '/')) for test in tests: output.write(test + '\n Check Test Case ${TESTNAME}\n\n') print outpath
[ [ 8, 0, 0.0957, 0.0851, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.1702, 0.0213, 0, 0.66, 0.125, 777, 0, 1, 0, 0, 777, 0, 0 ], [ 1, 0, 0.1915, 0.0213, 0, 0.66,...
[ "\"\"\"Script to generate atest runners based on data files.\n\nUsage: %s path/to/data.file\n\"\"\"", "from __future__ import with_statement", "import sys, os", "if len(sys.argv) != 2:\n print(__doc__ % os.path.basename(sys.argv[0]))\n sys.exit(1)", " print(__doc__ % os.path.basename(sys.argv[0]))...
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import inspect import sys from robot import utils from robot.errors import DataError from outputcapture import OutputCapturer from runkwregister import RUN_KW_REGISTER from keywords import Keywords, Keyword from arguments import (PythonKeywordArguments, JavaKeywordArguments, DynamicKeywordArguments, RunKeywordArguments, PythonInitArguments, JavaInitArguments) from signalhandler import STOP_SIGNAL_MONITOR if utils.is_jython: from org.python.core import PyReflectedFunction, PyReflectedConstructor def _is_java_init(init): return isinstance(init, PyReflectedConstructor) def _is_java_method(method): return hasattr(method, 'im_func') \ and isinstance(method.im_func, PyReflectedFunction) else: _is_java_init = _is_java_method = lambda item: False def Handler(library, name, method): if RUN_KW_REGISTER.is_run_keyword(library.orig_name, name): return _RunKeywordHandler(library, name, method) if _is_java_method(method): return _JavaHandler(library, name, method) else: return _PythonHandler(library, name, method) def DynamicHandler(library, name, method, doc, argspec): if RUN_KW_REGISTER.is_run_keyword(library.orig_name, name): return _DynamicRunKeywordHandler(library, name, method, doc, argspec) return _DynamicHandler(library, name, method, doc, argspec) def InitHandler(library, method): if method is None: method = lambda: None Init = _PythonInitHandler if not _is_java_init(method) else _JavaInitHandler return Init(library, '__init__', method) class _BaseHandler(object): type = 'library' doc = '' def __init__(self, library, handler_name, handler_method): self.library = library self.name = utils.printable_name(handler_name, code_style=True) self.arguments = self._parse_arguments(handler_method) def _parse_arguments(self, handler_method): raise NotImplementedError(self.__class__.__name__) @property def longname(self): return '%s.%s' % (self.library.name, self.name) @property def shortdoc(self): return self.doc.splitlines()[0] if self.doc else '' class _RunnableHandler(_BaseHandler): def __init__(self, library, handler_name, handler_method): _BaseHandler.__init__(self, library, handler_name, handler_method) self._handler_name = handler_name self._method = self._get_initial_handler(library, handler_name, handler_method) def _get_initial_handler(self, library, name, method): if library.scope == 'GLOBAL': return self._get_global_handler(method, name) return None def init_keyword(self, varz): pass def run(self, context, args): if context.dry_run: return self._dry_run(context, args) return self._run(context, args) def _dry_run(self, context, args): self.arguments.check_arg_limits_for_dry_run(args) return None def _run(self, context, args): output = context.output positional, named = \ self.arguments.resolve(args, context.get_current_vars(), output) runner = self._runner_for(self._current_handler(), output, positional, named, self._get_timeout(context.namespace)) return self._run_with_output_captured_and_signal_monitor(runner, context) def _runner_for(self, handler, output, positional, named, timeout): if timeout and timeout.active: output.debug(timeout.get_message()) return lambda: timeout.run(handler, args=positional, kwargs=named) return lambda: handler(*positional, **named) def _run_with_output_captured_and_signal_monitor(self, runner, context): capturer = OutputCapturer() try: return self._run_with_signal_monitoring(runner, context) finally: stdout, stderr = capturer.release() context.output.log_output(stdout) context.output.log_output(stderr) if stderr: sys.__stderr__.write(stderr+'\n') def _run_with_signal_monitoring(self, runner, context): try: STOP_SIGNAL_MONITOR.start_running_keyword(context.teardown) return runner() finally: STOP_SIGNAL_MONITOR.stop_running_keyword() def _current_handler(self): if self._method: return self._method return self._get_handler(self.library.get_instance(), self._handler_name) def _get_global_handler(self, method, name): return method def _get_handler(self, lib_instance, handler_name): return getattr(lib_instance, handler_name) def _get_timeout(self, namespace): timeoutable = self._get_timeoutable_items(namespace) if timeoutable: return min(item.timeout for item in timeoutable) return None def _get_timeoutable_items(self, namespace): items = namespace.uk_handlers[:] if self._test_running_and_not_in_teardown(namespace.test): items.append(namespace.test) return items def _test_running_and_not_in_teardown(self, test): return test and test.status == 'RUNNING' class _PythonHandler(_RunnableHandler): def __init__(self, library, handler_name, handler_method): _RunnableHandler.__init__(self, library, handler_name, handler_method) self.doc = inspect.getdoc(handler_method) or '' def _parse_arguments(self, handler_method): return PythonKeywordArguments(handler_method, self.longname) class _JavaHandler(_RunnableHandler): def _parse_arguments(self, handler_method): return JavaKeywordArguments(handler_method, self.longname) class _DynamicHandler(_RunnableHandler): def __init__(self, library, handler_name, handler_method, doc='', argspec=None): self._argspec = argspec _RunnableHandler.__init__(self, library, handler_name, handler_method) self._run_keyword_method_name = handler_method.__name__ self.doc = doc is not None and utils.unic(doc) or '' def _parse_arguments(self, handler_method): return DynamicKeywordArguments(self._argspec, self.longname) def _get_handler(self, lib_instance, handler_name): runner = getattr(lib_instance, self._run_keyword_method_name) return self._get_dynamic_handler(runner, handler_name) def _get_global_handler(self, method, name): return self._get_dynamic_handler(method, name) def _get_dynamic_handler(self, runner, name): def handler(*args): return runner(name, list(args)) return handler class _RunKeywordHandler(_PythonHandler): def __init__(self, library, handler_name, handler_method): _PythonHandler.__init__(self, library, handler_name, handler_method) self._handler_method = handler_method def _run_with_signal_monitoring(self, runner, context): # With run keyword variants, only the keyword to be run can fail # and therefore monitoring should not raise exception yet. return runner() def _parse_arguments(self, handler_method): arg_index = RUN_KW_REGISTER.get_args_to_process(self.library.orig_name, self.name) return RunKeywordArguments(handler_method, self.longname, arg_index) def _get_timeout(self, namespace): return None def _dry_run(self, context, args): _RunnableHandler._dry_run(self, context, args) keywords = self._get_runnable_keywords(context, args) keywords.run(context) def _get_runnable_keywords(self, context, args): keywords = Keywords([]) for keyword in self._get_keywords(args): if self._variable_syntax_in(keyword.name, context): continue keywords.add_keyword(keyword) return keywords def _get_keywords(self, args): arg_names = self.arguments.names if 'name' in arg_names: name_index = arg_names.index('name') return [ Keyword(args[name_index], args[name_index+1:]) ] elif self.arguments.varargs == 'names': return [ Keyword(name, []) for name in args[len(arg_names):] ] return [] def _variable_syntax_in(self, kw_name, context): try: resolved = context.namespace.variables.replace_string(kw_name) #Variable can contain value, but it might be wrong, #therefore it cannot be returned return resolved != kw_name except DataError: return True class _XTimesHandler(_RunKeywordHandler): def __init__(self, handler, name): _RunKeywordHandler.__init__(self, handler.library, handler.name, handler._handler_method) self.name = name self.doc = "*DEPRECATED* Replace X times syntax with 'Repeat Keyword'." def run(self, context, args): resolved_times = context.namespace.variables.replace_string(self.name) _RunnableHandler.run(self, context, [resolved_times] + args) @property def longname(self): return self.name class _DynamicRunKeywordHandler(_DynamicHandler, _RunKeywordHandler): _parse_arguments = _RunKeywordHandler._parse_arguments _get_timeout = _RunKeywordHandler._get_timeout class _PythonInitHandler(_PythonHandler): def _parse_arguments(self, handler_method): return PythonInitArguments(handler_method, self.library.name) class _JavaInitHandler(_BaseHandler): def _parse_arguments(self, handler_method): return JavaInitArguments(handler_method, self.library.name)
[ [ 1, 0, 0.0514, 0.0034, 0, 0.66, 0, 878, 0, 1, 0, 0, 878, 0, 0 ], [ 1, 0, 0.0548, 0.0034, 0, 0.66, 0.0455, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.0616, 0.0034, 0, ...
[ "import inspect", "import sys", "from robot import utils", "from robot.errors import DataError", "from outputcapture import OutputCapturer", "from runkwregister import RUN_KW_REGISTER", "from keywords import Keywords, Keyword", "from arguments import (PythonKeywordArguments, JavaKeywordArguments,\n ...
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. class SuiteRunErrors(object): _NO_ERROR = None _exit_on_failure_error = ('Critical failure occurred and ExitOnFailure ' 'option is in use') _exit_on_fatal_error = 'Test execution is stopped due to a fatal error' _parent_suite_init_error = 'Initialization of the parent suite failed.' _parent_suite_setup_error = 'Setup of the parent suite failed.' def __init__(self, run_mode_is_exit_on_failure=False, run_mode_skip_teardowns_on_exit=False): self._run_mode_is_exit_on_failure = run_mode_is_exit_on_failure self._run_mode_skip_teardowns_on_exit = run_mode_skip_teardowns_on_exit self._earlier_init_errors = [] self._earlier_setup_errors = [] self._earlier_suite_setup_executions = [] self._init_current_errors() self._exit_runmode = self._exit_fatal = False self._current_suite_setup_executed = False @property def exit(self): return self._exit_fatal or self._exit_runmode def _init_current_errors(self): self._current_init_err = self._current_setup_err = self._NO_ERROR def start_suite(self): self._earlier_init_errors.append(self._current_init_err) self._earlier_setup_errors.append(self._current_setup_err) self._earlier_suite_setup_executions.append(self._current_suite_setup_executed) self._init_current_errors() self._current_suite_setup_executed = False def end_suite(self): self._current_setup_err = self._earlier_setup_errors.pop() self._current_init_err = self._earlier_init_errors.pop() self._current_suite_setup_executed = self._earlier_suite_setup_executions.pop() def is_suite_setup_allowed(self): return self._current_init_err is self._NO_ERROR and \ not self._earlier_errors() def is_suite_teardown_allowed(self): if not self.is_test_teardown_allowed(): return False if self._current_suite_setup_executed: return True return self._current_init_err is self._NO_ERROR and \ not self._earlier_errors() def is_test_teardown_allowed(self): if not self._run_mode_skip_teardowns_on_exit: return True return not (self._exit_fatal or self._exit_runmode) def _earlier_errors(self): if self._exit_runmode or self._exit_fatal: return True for err in self._earlier_setup_errors + self._earlier_init_errors: if err is not self._NO_ERROR: return True return False def suite_init_err(self, error_message): self._current_init_err = error_message def setup_executed(self): self._current_suite_setup_executed = True def suite_setup_err(self, err): if err.exit: self._exit_fatal = True self._current_setup_err = unicode(err) def suite_error(self): if self._earlier_init_erros_occurred(): return self._parent_suite_init_error if self._earlier_setup_errors_occurred(): return self._parent_suite_setup_error if self._current_init_err: return self._current_init_err if self._current_setup_err: return 'Suite setup failed:\n%s' % self._current_setup_err return '' def _earlier_init_erros_occurred(self): return any(self._earlier_init_errors) def _earlier_setup_errors_occurred(self): return any(self._earlier_setup_errors) def child_error(self): if self._current_init_err or self._earlier_init_erros_occurred(): return self._parent_suite_init_error if self._current_setup_err or self._earlier_setup_errors_occurred(): return self._parent_suite_setup_error if self._exit_runmode: return self._exit_on_failure_error if self._exit_fatal: return self._exit_on_fatal_error return None def test_failed(self, exit=False, critical=False): if critical and self._run_mode_is_exit_on_failure: self._exit_runmode = True if exit: self._exit_fatal = True class TestRunErrors(object): def __init__(self, err): self._parent_err = err.child_error() if err else None self._init_err = None self._setup_err = None self._kw_err = None self._teardown_err = None def is_allowed_to_run(self): return not bool(self._parent_err or self._init_err) def init_err(self, err): self._init_err = err def setup_err(self, err): self._setup_err = err def setup_failed(self): return bool(self._setup_err) def kw_err(self, error): self._kw_err = error def teardown_err(self, err): self._teardown_err = err def teardown_failed(self): return bool(self._teardown_err) def get_message(self): if self._setup_err: return 'Setup failed:\n%s' % self._setup_err return self._kw_err def get_teardown_message(self, message): # TODO: This API is really in need of cleanup if message == '': return 'Teardown failed:\n%s' % self._teardown_err return '%s\n\nAlso teardown failed:\n%s' % (message, self._teardown_err) def parent_or_init_error(self): return self._parent_err or self._init_err class KeywordRunErrors(object): def __init__(self): self.teardown_error = None def get_message(self): if not self._teardown_err: return self._kw_err if not self._kw_err: return 'Keyword teardown failed:\n%s' % self._teardown_err return '%s\n\nAlso keyword teardown failed:\n%s' % (self._kw_err, self._teardown_err) def teardown_err(self, err): self.teardown_error = err
[ [ 3, 0, 0.3649, 0.573, 0, 0.66, 0, 239, 0, 17, 0, 0, 186, 0, 18 ], [ 14, 1, 0.0865, 0.0054, 1, 0.37, 0, 1, 1, 0, 0, 0, 0, 9, 0 ], [ 14, 1, 0.0946, 0.0108, 1, 0.37, ...
[ "class SuiteRunErrors(object):\n _NO_ERROR = None\n _exit_on_failure_error = ('Critical failure occurred and ExitOnFailure '\n 'option is in use')\n _exit_on_fatal_error = 'Test execution is stopped due to a fatal error'\n _parent_suite_init_error = 'Initialization of the pa...
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import sys from StringIO import StringIO class OutputCapturer: def __init__(self): self._python_out = _PythonCapturer(stdout=True) self._python_err = _PythonCapturer(stdout=False) self._java_out = _JavaCapturer(stdout=True) self._java_err = _JavaCapturer(stdout=False) def release(self): py_out = self._python_out.release() py_err = self._python_err.release() java_out = self._java_out.release() java_err = self._java_err.release() # FIXME: Should return both Python and Java stdout/stderr. # It is unfortunately not possible to do py_out+java_out here, because # java_out is always Unicode and py_out is bytes (=str). When py_out # contains non-ASCII bytes catenation fails with UnicodeError. # Unfortunately utils.unic(py_out) doesn't work either, because later # splitting the output to levels and messages fails. Should investigate # why that happens. It also seems that the byte message are never # converted to Unicode - at least Message class doesn't do that. # It's probably safe to leave this code like it is in RF 2.5, because # a) the earlier versions worked the same way, and b) this code is # used so that there should never be output both from Python and Java. return (py_out, py_err) if (py_out or py_err) else (java_out, java_err) class _PythonCapturer(object): def __init__(self, stdout=True): if stdout: self._original = sys.stdout self._set_stream = self._set_stdout else: self._original = sys.stderr self._set_stream = self._set_stderr self._stream = StringIO() self._set_stream(self._stream) def _set_stdout(self, stream): sys.stdout = stream def _set_stderr(self, stream): sys.stderr = stream def release(self): # Original stream must be restored before closing the current self._set_stream(self._original) self._stream.flush() output = self._stream.getvalue() self._stream.close() return output if not sys.platform.startswith('java'): class _JavaCapturer(object): def __init__(self, stdout): pass def release(self): return '' else: from java.io import PrintStream, ByteArrayOutputStream from java.lang import System class _JavaCapturer(object): def __init__(self, stdout=True): if stdout: self._original = System.out self._set_stream = System.setOut else: self._original = System.err self._set_stream = System.setErr self._bytes = ByteArrayOutputStream() self._stream = PrintStream(self._bytes, False, 'UTF-8') self._set_stream(self._stream) def release(self): # Original stream must be restored before closing the current self._set_stream(self._original) self._stream.close() output = self._bytes.toString('UTF-8') self._bytes.reset() return output
[ [ 1, 0, 0.1415, 0.0094, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.1509, 0.0094, 0, 0.66, 0.25, 609, 0, 1, 0, 0, 609, 0, 0 ], [ 3, 0, 0.2925, 0.2358, 0, 0....
[ "import sys", "from StringIO import StringIO", "class OutputCapturer:\n\n def __init__(self):\n self._python_out = _PythonCapturer(stdout=True)\n self._python_err = _PythonCapturer(stdout=False)\n self._java_out = _JavaCapturer(stdout=True)\n self._java_err = _JavaCapturer(stdout=...
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from fixture import Setup, Teardown from timeouts import TestTimeout class DefaultValues(object): def __init__(self, settings, parent_default_values=None): self._parent = parent_default_values self._setup = settings.test_setup self._teardown = settings.test_teardown self._timeout = settings.test_timeout self._force_tags = settings.force_tags self._default_tags = settings.default_tags self._test_template = settings.test_template def get_setup(self, tc_setup): setup = tc_setup if tc_setup.is_set() else self._get_default_setup() return Setup(setup.name, setup.args) def _get_default_setup(self): if self._setup.is_set() or not self._parent: return self._setup return self._parent._get_default_setup() def get_teardown(self, tc_teardown): td = tc_teardown if tc_teardown.is_set() else self._get_default_teardown() return Teardown(td.name, td.args) def _get_default_teardown(self): if self._teardown.is_set() or not self._parent: return self._teardown return self._parent._get_default_teardown() def get_timeout(self, tc_timeout): timeout = tc_timeout if tc_timeout.is_set() else self._timeout return TestTimeout(timeout.value, timeout.message) def get_tags(self, tc_tags): tags = tc_tags if tc_tags.is_set() else self._default_tags return (tags + self._get_force_tags()).value def _get_force_tags(self): if not self._parent: return self._force_tags return self._force_tags + self._parent._get_force_tags() def get_template(self, template): return (template if template.is_set() else self._test_template).value
[ [ 1, 0, 0.254, 0.0159, 0, 0.66, 0, 458, 0, 2, 0, 0, 458, 0, 0 ], [ 1, 0, 0.2698, 0.0159, 0, 0.66, 0.5, 164, 0, 1, 0, 0, 164, 0, 0 ], [ 3, 0, 0.6587, 0.6984, 0, 0.66...
[ "from fixture import Setup, Teardown", "from timeouts import TestTimeout", "class DefaultValues(object):\n\n def __init__(self, settings, parent_default_values=None):\n self._parent = parent_default_values\n self._setup = settings.test_setup\n self._teardown = settings.test_teardown\n ...
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import sys import inspect from array import ArrayType from robot.errors import DataError, FrameworkError from robot.variables import is_list_var, is_scalar_var from robot import utils if utils.is_jython: from javaargcoercer import ArgumentCoercer class _KeywordArguments(object): _type = 'Keyword' def __init__(self, argument_source, kw_or_lib_name): self.names, self.defaults, self.varargs, self.minargs, self.maxargs \ = self._determine_args(argument_source) self._arg_limit_checker = _ArgLimitChecker(self.minargs, self.maxargs, kw_or_lib_name, self._type) def _determine_args(self, handler_or_argspec): args, defaults, varargs = self._get_arg_spec(handler_or_argspec) minargs = len(args) - len(defaults) maxargs = len(args) if not varargs else sys.maxint return args, defaults, varargs, minargs, maxargs def resolve(self, args, variables, output=None): posargs, namedargs = self._resolve(args, variables, output) self.check_arg_limits(posargs, namedargs) self._tracelog_args(output, posargs, namedargs) return posargs, namedargs def _resolve(self, args, variables, output): return self._get_argument_resolver().resolve(args, output, variables) def check_arg_limits(self, args, namedargs={}): self._arg_limit_checker.check_arg_limits(args, namedargs) def check_arg_limits_for_dry_run(self, args): self._arg_limit_checker.check_arg_limits_for_dry_run(args) def _tracelog_args(self, logger, posargs, namedargs={}): if self._logger_not_available_during_library_init(logger): return args = [utils.safe_repr(a) for a in posargs] \ + ['%s=%s' % (utils.unic(a), utils.safe_repr(namedargs[a])) for a in namedargs] logger.trace('Arguments: [ %s ]' % ' | '.join(args)) def _logger_not_available_during_library_init(self, logger): return not logger class PythonKeywordArguments(_KeywordArguments): def _get_argument_resolver(self): return PythonKeywordArgumentResolver(self) def _get_arg_spec(self, handler): """Returns info about args in a tuple (args, defaults, varargs) args - list of all accepted arguments except varargs defaults - list of default values varargs - name of the argument accepting varargs or None """ args, varargs, _, defaults = inspect.getargspec(handler) if inspect.ismethod(handler): args = args[1:] # drop 'self' defaults = list(defaults) if defaults else [] return args, defaults, varargs class JavaKeywordArguments(_KeywordArguments): def __init__(self, handler_method, name): _KeywordArguments.__init__(self, handler_method, name) self.arg_coercer = ArgumentCoercer(self._get_signatures(handler_method)) def _get_argument_resolver(self): return JavaKeywordArgumentResolver(self) def _determine_args(self, handler_method): signatures = self._get_signatures(handler_method) minargs, maxargs = self._get_arg_limits(signatures) return [], [], None, minargs, maxargs def _get_signatures(self, handler): co = self._get_code_object(handler) return co.argslist[:co.nargs] def _get_code_object(self, handler): try: return handler.im_func except AttributeError: return handler def _get_arg_limits(self, signatures): if len(signatures) == 1: return self._get_single_sig_arg_limits(signatures[0]) else: return self._get_multi_sig_arg_limits(signatures) def _get_single_sig_arg_limits(self, signature): args = signature.args if len(args) > 0 and args[-1].isArray(): mina = len(args) - 1 maxa = sys.maxint else: mina = maxa = len(args) return mina, maxa def _get_multi_sig_arg_limits(self, signatures): mina = maxa = None for sig in signatures: argc = len(sig.args) if mina is None or argc < mina: mina = argc if maxa is None or argc > maxa: maxa = argc return mina, maxa class DynamicKeywordArguments(_KeywordArguments): def _get_argument_resolver(self): return PythonKeywordArgumentResolver(self) def _get_arg_spec(self, argspec): if argspec is None: return [], [], '<unknown>' try: if isinstance(argspec, basestring): raise TypeError return self._parse_arg_spec(list(argspec)) except TypeError: raise TypeError('Argument spec should be a list/array of strings') def _parse_arg_spec(self, argspec): if argspec == []: return [], [], None args = [] defaults = [] vararg = None for token in argspec: if vararg is not None: raise TypeError if token.startswith('*'): vararg = token[1:] continue if '=' in token: arg, default = token.split('=', 1) args.append(arg) defaults.append(default) continue if defaults: raise TypeError args.append(token) return args, defaults, vararg class RunKeywordArguments(PythonKeywordArguments): def __init__(self, argument_source, name, arg_resolution_index): PythonKeywordArguments.__init__(self, argument_source, name) self._arg_resolution_index = arg_resolution_index def _resolve(self, args, variables, output): args = variables.replace_from_beginning(self._arg_resolution_index, args) return args, {} class PythonInitArguments(PythonKeywordArguments): _type = 'Test Library' class JavaInitArguments(JavaKeywordArguments): _type = 'Test Library' def resolve(self, args, variables=None): if variables: args = variables.replace_list(args) self.check_arg_limits(args) return args, {} class UserKeywordArguments(object): def __init__(self, args, name): self.names, self.defaults, self.varargs = self._get_arg_spec(args) self.minargs = len(self.names) - len(self.defaults) maxargs = len(self.names) if not self.varargs else sys.maxint self._arg_limit_checker = _ArgLimitChecker(self.minargs, maxargs, name, 'Keyword') def _get_arg_spec(self, origargs): """Returns argument spec in a tuple (args, defaults, varargs). args - tuple of all accepted arguments defaults - tuple of default values varargs - name of the argument accepting varargs or None Examples: ['${arg1}', '${arg2}'] => ('${arg1}', '${arg2}'), (), None ['${arg1}', '${arg2}=default', '@{varargs}'] => ('${arg1}', '${arg2}'), ('default',), '@{varargs}' """ args = [] defaults = [] varargs = None for arg in origargs: if varargs: raise DataError('Only last argument can be a list') if is_list_var(arg): varargs = arg continue # should be last round (otherwise DataError in next) arg, default = self._split_default(arg) if defaults and default is None: raise DataError('Non default argument after default arguments') if not is_scalar_var(arg): raise DataError("Invalid argument '%s'" % arg) args.append(arg) if default is not None: defaults.append(default) return args, defaults, varargs def _split_default(self, arg): if '=' not in arg: return arg, None return arg.split('=', 1) def resolve_arguments_for_dry_run(self, arguments): self._arg_limit_checker.check_arg_limits_for_dry_run(arguments) required_number_of_args = self.minargs + len(self.defaults) needed_args = required_number_of_args - len(arguments) if needed_args > 0: return self._fill_missing_args(arguments, needed_args) return arguments def _fill_missing_args(self, arguments, needed): return arguments + needed * [None] def resolve(self, arguments, variables, output): positional, varargs, named = self._resolve_arg_usage(arguments, variables, output) self._arg_limit_checker.check_arg_limits(positional+varargs, named) argument_values = self._resolve_arg_values(variables, named, positional) argument_values += varargs self._arg_limit_checker.check_missing_args(argument_values, len(arguments)) return argument_values def _resolve_arg_usage(self, arguments, variables, output): resolver = UserKeywordArgumentResolver(self) positional, named = resolver.resolve(arguments, output=output) positional, named = self._replace_variables(variables, positional, named) return self._split_args_and_varargs(positional) + (named,) def _resolve_arg_values(self, variables, named, positional): template = self._template_for(variables) for name, value in named.items(): template.set_value(self.names.index(name), value) for index, value in enumerate(positional): template.set_value(index, value) return template.as_list() def _template_for(self, variables): defaults = variables.replace_list(list(self.defaults)) return UserKeywordArgsTemplate(self.minargs, defaults) def _replace_variables(self, variables, positional, named): for name in named: named[name] = variables.replace_scalar(named[name]) return variables.replace_list(positional), named def set_variables(self, arg_values, variables, output): before_varargs, varargs = self._split_args_and_varargs(arg_values) for name, value in zip(self.names, before_varargs): variables[name] = value if self.varargs: variables[self.varargs] = varargs self._tracelog_args(output, variables) def _split_args_and_varargs(self, args): if not self.varargs: return args, [] return args[:len(self.names)], args[len(self.names):] def _tracelog_args(self, logger, variables): arguments_string = self._get_arguments_as_string(variables) logger.trace('Arguments: [ %s ]' % arguments_string) def _get_arguments_as_string(self, variables): args = [] for name in self.names + ([self.varargs] if self.varargs else []): args.append('%s=%s' % (name, utils.safe_repr(variables[name]))) return ' | '.join(args) class _MissingArg(object): def __getattr__(self, name): raise DataError class UserKeywordArgsTemplate(object): def __init__(self, minargs, defaults): self._template = [_MissingArg() for _ in range(minargs)] + defaults self._already_set = set() def set_value(self, idx, value): if idx in self._already_set: raise FrameworkError self._already_set.add(idx) self._template[idx] = value def as_list(self): return self._template class _ArgumentResolver(object): def __init__(self, arguments): self._arguments = arguments self._mand_arg_count = len(arguments.names) - len(arguments.defaults) def resolve(self, values, output, variables=None): positional, named = self._resolve_argument_usage(values, output) return self._resolve_variables(positional, named, variables) def _resolve_argument_usage(self, values, output): named = {} last_positional = self._get_last_positional_idx(values) used_names = self._arguments.names[:last_positional] for arg in values[last_positional:]: name, value = self._parse_named(arg) if name in named: raise DataError('Keyword argument %s repeated.' % name) if name in used_names: output.warn("Could not resolve named arguments because value " "for argument '%s' was given twice." % name) return values, {} used_names.append(name) named[name] = value return values[:last_positional], named def _get_last_positional_idx(self, values): last_positional_idx = self._mand_arg_count named_allowed = True for arg in reversed(self._optional(values)): if not (named_allowed and self._is_named(arg)): named_allowed = False last_positional_idx += 1 return last_positional_idx def _optional(self, values): return values[self._mand_arg_count:] def _is_named(self, arg): if self._is_str_with_kwarg_sep(arg): name, _ = self._split_from_kwarg_sep(arg) return self._is_arg_name(name) return False def _parse_named(self, arg): name, value = self._split_from_kwarg_sep(arg) return self._coerce(name), value def _is_str_with_kwarg_sep(self, arg): if not isinstance(arg, basestring): return False if '=' not in arg: return False return True def _split_from_kwarg_sep(self, arg): return arg.split('=', 1) def _is_arg_name(self, name): return self._arg_name(name) in self._arguments.names def _resolve_variables(self, posargs, kwargs, variables): posargs = self._replace_list(posargs, variables) for name, value in kwargs.items(): kwargs[name] = self._replace_scalar(value, variables) return posargs, kwargs def _replace_list(self, values, variables): return variables.replace_list(values) if variables else values def _replace_scalar(self, value, variables): return variables.replace_scalar(value) if variables else value class UserKeywordArgumentResolver(_ArgumentResolver): def _arg_name(self, name): return '${%s}' % name def _coerce(self, name): return '${%s}' % name class PythonKeywordArgumentResolver(_ArgumentResolver): def _arg_name(self, name): return name def _coerce(self, name): return str(name) class JavaKeywordArgumentResolver(object): def __init__(self, arguments): self._arguments = arguments self._minargs, self._maxargs = arguments.minargs, arguments.maxargs def resolve(self, values, output, variables): values = variables.replace_list(values) self._arguments.check_arg_limits(values) if self._expects_varargs() and self._last_is_not_list(values): values[self._minargs:] = [values[self._minargs:]] return self._arguments.arg_coercer(values), {} def _expects_varargs(self): return self._maxargs == sys.maxint def _last_is_not_list(self, args): return not (len(args) == self._minargs + 1 and isinstance(args[-1], (list, tuple, ArrayType))) class _ArgLimitChecker(object): def __init__(self, minargs, maxargs, name, type_): self.minargs = minargs self.maxargs = maxargs self._name = name self._type = type_ def check_arg_limits(self, args, namedargs={}): self._check_arg_limits(len(args) + len(namedargs)) def check_arg_limits_for_dry_run(self, args): arg_count = len(args) scalar_arg_count = len([a for a in args if not is_list_var(a)]) if scalar_arg_count <= self.minargs and arg_count - scalar_arg_count: arg_count = self.minargs self._check_arg_limits(arg_count) def _check_arg_limits(self, arg_count): if not self.minargs <= arg_count <= self.maxargs: self._raise_inv_args(arg_count) def check_missing_args(self, args, arg_count): for a in args: if isinstance(a, _MissingArg): self._raise_inv_args(arg_count) def _raise_inv_args(self, arg_count): minend = utils.plural_or_not(self.minargs) if self.minargs == self.maxargs: exptxt = "%d argument%s" % (self.minargs, minend) elif self.maxargs != sys.maxint: exptxt = "%d to %d arguments" % (self.minargs, self.maxargs) else: exptxt = "at least %d argument%s" % (self.minargs, minend) raise DataError("%s '%s' expected %s, got %d." % (self._type, self._name, exptxt, arg_count))
[ [ 1, 0, 0.0311, 0.0021, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.0331, 0.0021, 0, 0.66, 0.0476, 878, 0, 1, 0, 0, 878, 0, 0 ], [ 1, 0, 0.0352, 0.0021, 0, ...
[ "import sys", "import inspect", "from array import ArrayType", "from robot.errors import DataError, FrameworkError", "from robot.variables import is_list_var, is_scalar_var", "from robot import utils", "if utils.is_jython:\n from javaargcoercer import ArgumentCoercer", " from javaargcoercer impo...
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import inspect from robot import utils class _RunKeywordRegister: def __init__(self): self._libs = {} def register_run_keyword(self, libname, keyword, args_to_process=None): if args_to_process is None: args_to_process = self._get_args_from_method(keyword) keyword = keyword.__name__ if libname not in self._libs: self._libs[libname] = utils.NormalizedDict(ignore=['_']) self._libs[libname][keyword] = int(args_to_process) def get_args_to_process(self, libname, kwname): if libname in self._libs and kwname in self._libs[libname]: return self._libs[libname][kwname] return -1 def is_run_keyword(self, libname, kwname): return self.get_args_to_process(libname, kwname) >= 0 def _get_args_from_method(self, method): if inspect.ismethod(method): return method.im_func.func_code.co_argcount -1 elif inspect.isfunction(method): return method.func_code.co_argcount raise ValueError("Needs function or method!") RUN_KW_REGISTER = _RunKeywordRegister()
[ [ 1, 0, 0.32, 0.02, 0, 0.66, 0, 878, 0, 1, 0, 0, 878, 0, 0 ], [ 1, 0, 0.36, 0.02, 0, 0.66, 0.3333, 735, 0, 1, 0, 0, 735, 0, 0 ], [ 3, 0, 0.68, 0.54, 0, 0.66, 0....
[ "import inspect", "from robot import utils", "class _RunKeywordRegister:\n\n def __init__(self):\n self._libs = {}\n\n def register_run_keyword(self, libname, keyword, args_to_process=None):\n if args_to_process is None:\n args_to_process = self._get_args_from_method(keyword)", ...
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from model import TestSuite from keywords import Keyword from testlibraries import TestLibrary from runkwregister import RUN_KW_REGISTER from signalhandler import STOP_SIGNAL_MONITOR def UserLibrary(path): """Create a user library instance from given resource file. This is used at least by libdoc.py.""" from robot.parsing import ResourceFile from robot import utils from arguments import UserKeywordArguments from userkeyword import UserLibrary as RuntimeUserLibrary resource = ResourceFile(path) ret = RuntimeUserLibrary(resource.keyword_table.keywords, path) for handler in ret.handlers.values(): # This is done normally only at runtime. handler.arguments = UserKeywordArguments(handler._keyword_args, handler.longname) handler.doc = utils.unescape(handler._doc) ret.doc = resource.setting_table.doc.value return ret class _Namespaces: def __init__(self): self._namespaces = [] self.current = None def start_suite(self, namespace): self._namespaces.append(self.current) self.current = namespace def end_suite(self): self.current = self._namespaces.pop() def __iter__(self): namespaces = self._namespaces + [self.current] return iter([ns for ns in namespaces if ns is not None]) # Hook to namespaces NAMESPACES = _Namespaces()
[ [ 1, 0, 0.2623, 0.0164, 0, 0.66, 0, 722, 0, 1, 0, 0, 722, 0, 0 ], [ 1, 0, 0.2787, 0.0164, 0, 0.66, 0.1429, 211, 0, 1, 0, 0, 211, 0, 0 ], [ 1, 0, 0.2951, 0.0164, 0, ...
[ "from model import TestSuite", "from keywords import Keyword", "from testlibraries import TestLibrary", "from runkwregister import RUN_KW_REGISTER", "from signalhandler import STOP_SIGNAL_MONITOR", "def UserLibrary(path):\n \"\"\"Create a user library instance from given resource file.\n\n This is u...
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import sys from java.lang import Byte, Short, Integer, Long, Boolean, Float, Double class ArgumentCoercer: def __init__(self, signatures): types = self._parse_types(signatures) self._coercers = [_CoercionFunction(t, i+1) for i, t in types] def _parse_types(self, signatures): types = {} for sig in signatures: for index, arg in enumerate(sig.args): types.setdefault(index, []).append(arg) return sorted(types.items()) def __call__(self, args): return [coercer(arg) for coercer, arg in zip(self._coercers, args)] class _CoercionFunction: _bool_types = [Boolean] _int_types = [Byte, Short, Integer, Long] _float_types = [Float, Double] _bool_primitives = ['boolean'] _int_primitives = ['byte', 'short', 'int', 'long'] _float_primitives = ['float', 'double'] _bool_primitives = ["<type 'boolean'>"] _int_primitives = ["<type '%s'>" % p for p in _int_primitives] _float_primitives = ["<type '%s'>" % p for p in _float_primitives] def __init__(self, arg_types, position): self._position = position self.__coercer = None for arg in arg_types: if not (self._set_bool(arg) or self._set_int(arg) or self._set_float(arg)): self.__coercer = self._no_coercion def __call__(self, arg): if not isinstance(arg, basestring): return arg return self.__coercer(arg) def _set_bool(self, arg): return self._set_coercer(arg, self._bool_types, self._bool_primitives, self._to_bool) def _set_int(self, arg): return self._set_coercer(arg, self._int_types, self._int_primitives, self._to_int) def _set_float(self, arg): return self._set_coercer(arg, self._float_types, self._float_primitives, self._to_float) def _set_coercer(self, arg, type_list, primitive_list, coercer): if arg in type_list or str(arg) in primitive_list: if self.__coercer is None: self.__coercer = coercer elif self.__coercer != coercer: self.__coercer = self._no_coercion return True return False def _to_bool(self, arg): try: return {'false': False, 'true': True}[arg.lower()] except KeyError: self._coercion_failed('boolean') def _to_int(self, arg): try: return int(arg) except ValueError: self._coercion_failed('integer') def _to_float(self, arg): try: return float(arg) except ValueError: self._coercion_failed('floating point number') def _no_coercion(self, arg): return arg def _coercion_failed(self, arg_type): raise ValueError('Argument at position %d cannot be coerced to %s' % (self._position, arg_type))
[ [ 1, 0, 0.1429, 0.0095, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.1524, 0.0095, 0, 0.66, 0.3333, 100, 0, 7, 0, 0, 100, 0, 0 ], [ 3, 0, 0.2476, 0.1429, 0, ...
[ "import sys", "from java.lang import Byte, Short, Integer, Long, Boolean, Float, Double", "class ArgumentCoercer:\n\n def __init__(self, signatures):\n types = self._parse_types(signatures)\n self._coercers = [_CoercionFunction(t, i+1) for i, t in types]\n\n def _parse_types(self, signatures...
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from robot.variables import GLOBAL_VARIABLES class ExecutionContext(object): def __init__(self, namespace, output, dry_run=False): self.namespace = namespace self.output = output self.dry_run = dry_run self._in_teardown = 0 @property def teardown(self): if self._in_teardown: return True # TODO: tests and suites should also call start/end_teardown() test_or_suite = self.namespace.test or self.namespace.suite return test_or_suite.status != 'RUNNING' def start_teardown(self): self._in_teardown += 1 def end_teardown(self): self._in_teardown -= 1 def get_current_vars(self): return self.namespace.variables def end_test(self, test): self.output.end_test(test) self.namespace.end_test() def end_suite(self, suite): self.output.end_suite(suite) self.namespace.end_suite() def output_file_changed(self, filename): self._set_global_variable('${OUTPUT_FILE}', filename) def replace_vars_from_setting(self, name, value, errors): return self.namespace.variables.replace_meta(name, value, errors) def log_file_changed(self, filename): self._set_global_variable('${LOG_FILE}', filename) def set_prev_test_variables(self, test): self._set_prev_test_variables(self.get_current_vars(), test.name, test.status, test.message) def copy_prev_test_vars_to_global(self): varz = self.get_current_vars() name, status, message = varz['${PREV_TEST_NAME}'], \ varz['${PREV_TEST_STATUS}'], varz['${PREV_TEST_MESSAGE}'] self._set_prev_test_variables(GLOBAL_VARIABLES, name, status, message) def _set_prev_test_variables(self, destination, name, status, message): destination['${PREV_TEST_NAME}'] = name destination['${PREV_TEST_STATUS}'] = status destination['${PREV_TEST_MESSAGE}'] = message def _set_global_variable(self, name, value): self.namespace.variables.set_global(name, value) def report_suite_status(self, status, message): self.get_current_vars()['${SUITE_STATUS}'] = status self.get_current_vars()['${SUITE_MESSAGE}'] = message def start_test(self, test): self.namespace.start_test(test) self.output.start_test(test) def set_test_status_before_teardown(self, message, status): self.namespace.set_test_status_before_teardown(message, status) def get_handler(self, name): return self.namespace.get_handler(name) def start_keyword(self, keyword): self.output.start_keyword(keyword) def end_keyword(self, keyword): self.output.end_keyword(keyword) def warn(self, message): self.output.warn(message) def trace(self, message): self.output.trace(message)
[ [ 1, 0, 0.1471, 0.0098, 0, 0.66, 0, 595, 0, 1, 0, 0, 595, 0, 0 ], [ 3, 0, 0.5882, 0.8333, 0, 0.66, 1, 63, 0, 22, 0, 0, 186, 0, 22 ], [ 2, 1, 0.2157, 0.049, 1, 0.92,...
[ "from robot.variables import GLOBAL_VARIABLES", "class ExecutionContext(object):\n\n def __init__(self, namespace, output, dry_run=False):\n self.namespace = namespace\n self.output = output\n self.dry_run = dry_run\n self._in_teardown = 0", " def __init__(self, namespace, outp...
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os.path import copy from robot.output import LOGGER from robot.parsing import ResourceFile from robot.errors import FrameworkError from robot import utils from testlibraries import TestLibrary class Importer: def __init__(self): self._library_cache = ImportCache() self._resource_cache = ImportCache() def import_library(self, name, args, alias, variables): lib = TestLibrary(name, args, variables, create_handlers=False) positional, named = lib.positional_args, lib.named_args lib = self._import_library(name, positional, named, lib) if alias and name != alias: lib = self._copy_library(lib, alias) LOGGER.info("Imported library '%s' with name '%s'" % (name, alias)) return lib def import_resource(self, path): if path in self._resource_cache: LOGGER.info("Found resource file '%s' from cache" % path) else: resource = ResourceFile(path) self._resource_cache[path] = resource return self._resource_cache[path] def _import_library(self, name, positional, named, lib): key = (name, positional, named) if key in self._library_cache: LOGGER.info("Found test library '%s' with arguments %s from cache" % (name, utils.seq2str2(positional))) return self._library_cache[key] lib.create_handlers() self._library_cache[key] = lib libtype = lib.__class__.__name__.replace('Library', '').lower()[1:] LOGGER.info("Imported library '%s' with arguments %s (version %s, " "%s type, %s scope, %d keywords, source %s)" % (name, utils.seq2str2(positional), lib.version, libtype, lib.scope.lower(), len(lib), lib.source)) if len(lib) == 0: LOGGER.warn("Imported library '%s' contains no keywords" % name) return lib def _copy_library(self, lib, newname): libcopy = copy.copy(lib) libcopy.name = newname libcopy.init_scope_handling() libcopy.handlers = utils.NormalizedDict(ignore=['_']) for handler in lib.handlers.values(): handcopy = copy.copy(handler) handcopy.library = libcopy libcopy.handlers[handler.name] = handcopy return libcopy class ImportCache: """Keeps track on and optionally caches imported items. Handles paths in keys case-insensitively on case-insensitive OSes. Unlike dicts, this storage accepts mutable values in keys. """ def __init__(self): self._keys = [] self._items = [] def __setitem__(self, key, item): if not isinstance(key, (basestring, tuple)): raise FrameworkError('Invalid key for ImportCache') self._keys.append(self._norm_path_key(key)) self._items.append(item) def add(self, key, item=None): self.__setitem__(key, item) def __getitem__(self, key): key = self._norm_path_key(key) if key not in self._keys: raise KeyError return self._items[self._keys.index(key)] def __contains__(self, key): return self._norm_path_key(key) in self._keys def _norm_path_key(self, key): if isinstance(key, tuple): return tuple(self._norm_path_key(k) for k in key) if isinstance(key, basestring) and os.path.exists(key): return utils.normpath(key) return key
[ [ 1, 0, 0.1339, 0.0089, 0, 0.66, 0, 79, 0, 1, 0, 0, 79, 0, 0 ], [ 1, 0, 0.1429, 0.0089, 0, 0.66, 0.125, 739, 0, 1, 0, 0, 739, 0, 0 ], [ 1, 0, 0.1607, 0.0089, 0, 0.6...
[ "import os.path", "import copy", "from robot.output import LOGGER", "from robot.parsing import ResourceFile", "from robot.errors import FrameworkError", "from robot import utils", "from testlibraries import TestLibrary", "class Importer:\n\n def __init__(self):\n self._library_cache = Import...
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import inspect from robot import utils from robot.errors import DataError from robot.common import BaseLibrary from robot.output import LOGGER from handlers import Handler, InitHandler, DynamicHandler if utils.is_jython: from org.python.core import PyReflectedFunction, PyReflectedConstructor from java.lang import Object else: Object = None def TestLibrary(name, args=None, variables=None, create_handlers=True): libcode, source = utils.import_(name) libclass = _get_lib_class(libcode) lib = libclass(libcode, source, name, args or [], variables) if create_handlers: lib.create_handlers() return lib def _get_lib_class(libcode): if inspect.ismodule(libcode): return _ModuleLibrary if _DynamicMethod(libcode, 'get_keyword_names'): if _DynamicMethod(libcode, 'run_keyword'): return _DynamicLibrary else: return _HybridLibrary return _ClassLibrary class _DynamicMethod(object): def __init__(self, libcode, underscore_name, default=None): self._method = self._get_method(libcode, underscore_name) self._default = default def __call__(self, *args): if not self._method: return self._default try: return self._method(*args) except: raise DataError("Calling dynamic method '%s' failed: %s" % (self._method.__name__, utils.get_error_message())) def __nonzero__(self): return self._method is not None def _get_method(self, libcode, underscore_name): for name in underscore_name, self._getCamelCaseName(underscore_name): method = getattr(libcode, name, None) if callable(method): return method return None def _getCamelCaseName(self, underscore_name): tokens = underscore_name.split('_') return ''.join([tokens[0]] + [t.capitalize() for t in tokens[1:]]) class _BaseTestLibrary(BaseLibrary): supports_named_arguments = False # this attribute is for libdoc _log_success = LOGGER.debug _log_failure = LOGGER.info _log_failure_details = LOGGER.debug def __init__(self, libcode, source, name, args, variables): if os.path.exists(name): name = os.path.splitext(os.path.basename(os.path.abspath(name)))[0] self.source = source self.version = self._get_version(libcode) self.name = name self.orig_name = name # Stores original name also after copying self.positional_args = [] self.named_args = {} self._instance_cache = [] self._libinst = None if libcode is not None: self.doc = inspect.getdoc(libcode) or '' self.scope = self._get_scope(libcode) self._libcode = libcode self.init = self._create_init_handler(libcode) self.positional_args, self.named_args = self.init.arguments.resolve(args, variables) def create_handlers(self): if self._libcode: self._libinst = self.get_instance() self.handlers = self._create_handlers(self._libinst) self.init_scope_handling() def start_suite(self): pass def end_suite(self): pass def start_test(self): pass def end_test(self): pass def _get_version(self, code): try: return str(code.ROBOT_LIBRARY_VERSION) except AttributeError: try: return str(code.__version__) except AttributeError: return '<unknown>' def _create_init_handler(self, libcode): init_method = getattr(libcode, '__init__', None) if not self._valid_init(init_method): init_method = None return InitHandler(self, init_method) def _valid_init(self, init_method): if inspect.ismethod(init_method): return True if utils.is_jython and isinstance(init_method, PyReflectedConstructor): return True return False def init_scope_handling(self): if self.scope == 'GLOBAL': return self._libinst = None self.start_suite = self._caching_start self.end_suite = self._restoring_end if self.scope == 'TESTCASE': self.start_test = self._caching_start self.end_test = self._restoring_end def _caching_start(self): self._instance_cache.append(self._libinst) self._libinst = None def _restoring_end(self): self._libinst = self._instance_cache.pop() def _get_scope(self, libcode): try: scope = libcode.ROBOT_LIBRARY_SCOPE scope = utils.normalize(scope, ignore=['_']).upper() except (AttributeError, TypeError): scope = 'TESTCASE' return scope if scope in ['GLOBAL','TESTSUITE'] else 'TESTCASE' def get_instance(self): if self._libinst is None: self._libinst = self._get_instance() return self._libinst def _get_instance(self): try: return self._libcode(*self.positional_args, **self.named_args) except: self._raise_creating_instance_failed() def _create_handlers(self, libcode): handlers = utils.NormalizedDict(ignore=['_']) for name in self._get_handler_names(libcode): method = self._try_to_get_handler_method(libcode, name) if method: handler = self._try_to_create_handler(name, method) if handler: handlers[name] = handler self._log_success("Created keyword '%s'" % handler.name) return handlers def _get_handler_names(self, libcode): return [name for name in dir(libcode) if not name.startswith(('_', 'ROBOT_LIBRARY_'))] def _try_to_get_handler_method(self, libcode, name): try: return self._get_handler_method(libcode, name) except: self._report_adding_keyword_failed(name) def _report_adding_keyword_failed(self, name): msg, details = utils.get_error_details() self._log_failure("Adding keyword '%s' to library '%s' failed: %s" % (name, self.name, msg)) if details: self._log_failure_details('Details:\n%s' % details) def _get_handler_method(self, libcode, name): method = getattr(libcode, name) if not inspect.isroutine(method): raise DataError('Not a method or function') return method def _try_to_create_handler(self, name, method): try: return self._create_handler(name, method) except: self._report_adding_keyword_failed(name) def _create_handler(self, handler_name, handler_method): return Handler(self, handler_name, handler_method) def _raise_creating_instance_failed(self): msg, details = utils.get_error_details() if self.positional_args: args = "argument%s %s" % (utils.plural_or_not(self.positional_args), utils.seq2str(self.positional_args)) else: args = "no arguments" raise DataError("Creating an instance of the test library '%s' with %s " "failed: %s\n%s" % (self.name, args, msg, details)) class _ClassLibrary(_BaseTestLibrary): supports_named_arguments = True # this attribute is for libdoc def _get_handler_method(self, libinst, name): # Type is checked before using getattr to avoid calling properties, # most importantly bean properties generated by Jython (issue 188). for item in (libinst,) + inspect.getmro(libinst.__class__): if item in (object, Object): continue if not (hasattr(item, '__dict__') and name in item.__dict__): continue self._validate_handler(item.__dict__[name]) return getattr(libinst, name) raise DataError('No non-implicit implementation found') def _validate_handler(self, handler): if not self._is_routine(handler): raise DataError('Not a method or function') if self._is_implicit_java_or_jython_method(handler): raise DataError('Implicit methods are ignored') def _is_routine(self, handler): # inspect.isroutine doesn't work with methods from Java classes # prior to Jython 2.5.2: http://bugs.jython.org/issue1223 return inspect.isroutine(handler) or self._is_java_method(handler) def _is_java_method(self, handler): return utils.is_jython and isinstance(handler, PyReflectedFunction) def _is_implicit_java_or_jython_method(self, handler): if not self._is_java_method(handler): return False for signature in handler.argslist[:handler.nargs]: cls = signature.declaringClass if not (cls is Object or self._is_created_by_jython(handler, cls)): return False return True def _is_created_by_jython(self, handler, cls): proxy_methods = getattr(cls, '__supernames__', []) + ['classDictInit'] return handler.__name__ in proxy_methods class _ModuleLibrary(_BaseTestLibrary): supports_named_arguments = True # this attribute is for libdoc def _get_scope(self, libcode): return 'GLOBAL' def _get_handler_method(self, libcode, name): method = _BaseTestLibrary._get_handler_method(self, libcode, name) if hasattr(libcode, '__all__') and name not in libcode.__all__: raise DataError('Not exposed as a keyword') return method def get_instance(self): self.init.arguments.check_arg_limits(self.positional_args) return self._libcode def _create_init_handler(self, libcode): return InitHandler(self, None) class _HybridLibrary(_BaseTestLibrary): _log_failure = LOGGER.warn def _get_handler_names(self, instance): try: return instance.get_keyword_names() except AttributeError: return instance.getKeywordNames() class _DynamicLibrary(_BaseTestLibrary): _log_failure = LOGGER.warn def __init__(self, libcode, source, name, args, variables=None): _BaseTestLibrary.__init__(self, libcode, source, name, args, variables) self._get_kw_doc = \ _DynamicMethod(libcode, 'get_keyword_documentation', default='') self._get_kw_args = \ _DynamicMethod(libcode, 'get_keyword_arguments', default=None) def _get_handler_names(self, instance): try: return instance.get_keyword_names() except AttributeError: return instance.getKeywordNames() def _get_handler_method(self, instance, name_is_ignored): try: return instance.run_keyword except AttributeError: return instance.runKeyword def _create_handler(self, handler_name, handler_method): doc = self._get_kw_doc(self._libinst, handler_name) argspec = self._get_kw_args(self._libinst, handler_name) return DynamicHandler(self, handler_name, handler_method, doc, argspec)
[ [ 1, 0, 0.0449, 0.003, 0, 0.66, 0, 688, 0, 1, 0, 0, 688, 0, 0 ], [ 1, 0, 0.0479, 0.003, 0, 0.66, 0.0667, 878, 0, 1, 0, 0, 878, 0, 0 ], [ 1, 0, 0.0539, 0.003, 0, 0.6...
[ "import os", "import inspect", "from robot import utils", "from robot.errors import DataError", "from robot.common import BaseLibrary", "from robot.output import LOGGER", "from handlers import Handler, InitHandler, DynamicHandler", "if utils.is_jython:\n from org.python.core import PyReflectedFunct...
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. class VariableSplitter: def __init__(self, string, identifiers): self.identifier = None self.base = None self.index = None self.start = -1 self.end = -1 self._identifiers = identifiers self._may_have_internal_variables = False try: self._split(string) except ValueError: pass else: self._finalize() def get_replaced_base(self, variables): if self._may_have_internal_variables: return variables.replace_string(self.base) return self.base def _finalize(self): self.identifier = self._variable_chars[0] self.base = ''.join(self._variable_chars[2:-1]) self.end = self.start + len(self._variable_chars) if self._has_list_variable_index(): self.index = ''.join(self._list_variable_index_chars[1:-1]) self.end += len(self._list_variable_index_chars) def _has_list_variable_index(self): return self._list_variable_index_chars \ and self._list_variable_index_chars[-1] == ']' def _split(self, string): start_index, max_index = self._find_variable(string) self.start = start_index self._open_curly = 1 self._state = self._variable_state self._variable_chars = [string[start_index], '{'] self._list_variable_index_chars = [] self._string = string start_index += 2 for index, char in enumerate(string[start_index:]): index += start_index # Giving start to enumerate only in Py 2.6+ try: self._state(char, index) except StopIteration: return if index == max_index and not self._scanning_list_variable_index(): return def _scanning_list_variable_index(self): return self._state in [self._waiting_list_variable_index_state, self._list_variable_index_state] def _find_variable(self, string): max_end_index = string.rfind('}') if max_end_index == -1: return ValueError('No variable end found') if self._is_escaped(string, max_end_index): return self._find_variable(string[:max_end_index]) start_index = self._find_start_index(string, 1, max_end_index) if start_index == -1: return ValueError('No variable start found') return start_index, max_end_index def _find_start_index(self, string, start, end): index = string.find('{', start, end) - 1 if index < 0: return -1 if self._start_index_is_ok(string, index): return index return self._find_start_index(string, index+2, end) def _start_index_is_ok(self, string, index): return string[index] in self._identifiers \ and not self._is_escaped(string, index) def _is_escaped(self, string, index): escaped = False while index > 0 and string[index-1] == '\\': index -= 1 escaped = not escaped return escaped def _variable_state(self, char, index): self._variable_chars.append(char) if char == '}' and not self._is_escaped(self._string, index): self._open_curly -= 1 if self._open_curly == 0: if not self._is_list_variable(): raise StopIteration self._state = self._waiting_list_variable_index_state elif char in self._identifiers: self._state = self._internal_variable_start_state def _is_list_variable(self): return self._variable_chars[0] == '@' def _internal_variable_start_state(self, char, index): self._state = self._variable_state if char == '{': self._variable_chars.append(char) self._open_curly += 1 self._may_have_internal_variables = True else: self._variable_state(char, index) def _waiting_list_variable_index_state(self, char, index): if char != '[': raise StopIteration self._list_variable_index_chars.append(char) self._state = self._list_variable_index_state def _list_variable_index_state(self, char, index): self._list_variable_index_chars.append(char) if char == ']': raise StopIteration
[ [ 3, 0, 0.5597, 0.8881, 0, 0.66, 0, 73, 0, 15, 0, 0, 0, 0, 29 ], [ 2, 1, 0.1828, 0.1045, 1, 0.37, 0, 555, 0, 3, 0, 0, 0, 0, 2 ], [ 14, 2, 0.1418, 0.0075, 2, 0.47, ...
[ "class VariableSplitter:\n\n def __init__(self, string, identifiers):\n self.identifier = None\n self.base = None\n self.index = None\n self.start = -1\n self.end = -1", " def __init__(self, string, identifiers):\n self.identifier = None\n self.base = None\n ...
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. def is_var(string): if not isinstance(string, basestring): return False length = len(string) return length > 3 and string[0] in ['$','@'] and string.rfind('{') == 1 \ and string.find('}') == length - 1 def is_scalar_var(string): return is_var(string) and string[0] == '$' def is_list_var(string): return is_var(string) and string[0] == '@'
[ [ 2, 0, 0.6379, 0.2069, 0, 0.66, 0, 481, 0, 1, 1, 0, 0, 0, 4 ], [ 4, 1, 0.6034, 0.069, 1, 0.84, 0, 0, 0, 0, 0, 0, 0, 0, 1 ], [ 13, 2, 0.6207, 0.0345, 2, 0.37, 0...
[ "def is_var(string):\n if not isinstance(string, basestring):\n return False\n length = len(string)\n return length > 3 and string[0] in ['$','@'] and string.rfind('{') == 1 \\\n and string.find('}') == length - 1", " if not isinstance(string, basestring):\n return False", "...
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import tempfile from robot import utils from robot.output import LOGGER from variables import Variables from variablesplitter import VariableSplitter from isvar import is_var, is_scalar_var, is_list_var GLOBAL_VARIABLES = Variables() def init_global_variables(settings): _set_cli_vars(settings) for name, value in [ ('${TEMPDIR}', utils.abspath(tempfile.gettempdir())), ('${EXECDIR}', utils.abspath('.')), ('${/}', os.sep), ('${:}', os.pathsep), ('${SPACE}', ' '), ('${EMPTY}', ''), ('${True}', True), ('${False}', False), ('${None}', None), ('${null}', None), ('${OUTPUT_DIR}', settings['OutputDir']), ('${OUTPUT_FILE}', settings['Output']), ('${SUMMARY_FILE}', settings['Summary']), ('${REPORT_FILE}', settings['Report']), ('${LOG_FILE}', settings['Log']), ('${DEBUG_FILE}', settings['DebugFile']), ('${PREV_TEST_NAME}', ''), ('${PREV_TEST_STATUS}', ''), ('${PREV_TEST_MESSAGE}', '') ]: GLOBAL_VARIABLES[name] = value def _set_cli_vars(settings): for path, args in settings['VariableFiles']: try: GLOBAL_VARIABLES.set_from_file(path, args) except: msg, details = utils.get_error_details() LOGGER.error(msg) LOGGER.info(details) for varstr in settings['Variables']: try: name, value = varstr.split(':', 1) except ValueError: name, value = varstr, '' GLOBAL_VARIABLES['${%s}' % name] = value
[ [ 1, 0, 0.2273, 0.0152, 0, 0.66, 0, 688, 0, 1, 0, 0, 688, 0, 0 ], [ 1, 0, 0.2424, 0.0152, 0, 0.66, 0.1111, 516, 0, 1, 0, 0, 516, 0, 0 ], [ 1, 0, 0.2727, 0.0152, 0, ...
[ "import os", "import tempfile", "from robot import utils", "from robot.output import LOGGER", "from variables import Variables", "from variablesplitter import VariableSplitter", "from isvar import is_var, is_scalar_var, is_list_var", "GLOBAL_VARIABLES = Variables()", "def init_global_variables(setti...
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Module that adds directories needed by Robot to sys.path when imported.""" import sys import os import fnmatch def add_path(path, to_beginning=False, force=False): if _should_be_added(path, force): if to_beginning: sys.path.insert(0, path) else: sys.path.append(path) def remove_path(path): path = _normpath(path) sys.path = [p for p in sys.path if _normpath(p) != path] def _should_be_added(path, force): if (not path) or _find_in_syspath_normalized(path): return False return force or os.path.exists(path) def _find_in_syspath_normalized(path): path = _normpath(path) for element in sys.path: if _normpath(element) == path: return element return None def _normpath(path): return os.path.normcase(os.path.normpath(path)) ROBOTDIR = os.path.dirname(os.path.abspath(__file__)) PARENTDIR = os.path.dirname(ROBOTDIR) add_path(os.path.join(ROBOTDIR, 'libraries'), to_beginning=True, force=True) add_path(PARENTDIR, to_beginning=True) # Handles egg installations if fnmatch.fnmatchcase(os.path.basename(PARENTDIR), 'robotframework-*.egg'): add_path(os.path.dirname(PARENTDIR), to_beginning=True) # Remove ROBOTDIR dir to disallow importing robot internal modules directly remove_path(ROBOTDIR) # Elements from PYTHONPATH. By default it is not processed in Jython and in # Python valid non-absolute paths may be ignored. PYPATH = os.environ.get('PYTHONPATH') if PYPATH: for path in PYPATH.split(os.pathsep): add_path(path) del path # Current dir (it seems to be in Jython by default so let's be consistent) add_path('.') del _find_in_syspath_normalized, _normpath, add_path, remove_path, ROBOTDIR, PARENTDIR, PYPATH
[ [ 8, 0, 0.2162, 0.0135, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.2432, 0.0135, 0, 0.66, 0.0588, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.2568, 0.0135, 0, 0.66...
[ "\"\"\"Module that adds directories needed by Robot to sys.path when imported.\"\"\"", "import sys", "import os", "import fnmatch", "def add_path(path, to_beginning=False, force=False):\n if _should_be_added(path, force):\n if to_beginning:\n sys.path.insert(0, path)\n else:\n ...
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import sys import threading class Thread(threading.Thread): """A subclass of threading.Thread, with a stop() method. Original version posted by Connelly Barnes to python-list and available at http://mail.python.org/pipermail/python-list/2004-May/219465.html This version mainly has kill() changed to stop() to match java.lang.Thread. This is a hack but seems to be the best way the get this done. Only used in Python because in Jython we can use java.lang.Thread. """ def __init__(self, runner): threading.Thread.__init__(self, target=runner) self._stopped = False def start(self): self.__run_backup = self.run self.run = self.__run threading.Thread.start(self) def stop(self): self._stopped = True def __run(self): """Hacked run function, which installs the trace.""" sys.settrace(self._globaltrace) self.__run_backup() self.run = self.__run_backup def _globaltrace(self, frame, why, arg): if why == 'call': return self._localtrace else: return None def _localtrace(self, frame, why, arg): if self._stopped: if why == 'line': raise SystemExit() return self._localtrace
[ [ 1, 0, 0.2542, 0.0169, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.2712, 0.0169, 0, 0.66, 0.5, 83, 0, 1, 0, 0, 83, 0, 0 ], [ 3, 0, 0.661, 0.6949, 0, 0.66, ...
[ "import sys", "import threading", "class Thread(threading.Thread):\n \"\"\"A subclass of threading.Thread, with a stop() method.\n\n Original version posted by Connelly Barnes to python-list and available at\n http://mail.python.org/pipermail/python-list/2004-May/219465.html\n\n This version mainly ...
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import re from unic import unic def html_escape(text, formatting=False): # TODO: Remove formatting attribute after RIDE does not use it anymore if formatting: return html_format(text) return _HtmlEscaper().format(text) def html_format(text): return _HtmlFormatter().format(text) def html_attr_escape(attr): for name, value in [('&', '&amp;'), ('"', '&quot;'), ('<', '&lt;'), ('>', '&gt;')]: attr = attr.replace(name, value) for wspace in ['\n', '\r', '\t']: attr = attr.replace(wspace, ' ') return attr class _Formatter(object): def format(self, text): text = self._html_escape(unic(text)) for line in text.splitlines(): self.add_line(line) return self.get_result() def _html_escape(self, text): for name, value in [('&', '&amp;'), ('<', '&lt;'), ('>', '&gt;')]: text = text.replace(name, value) return text class _HtmlEscaper(_Formatter): def __init__(self): self._lines = [] self._line_formatter = _UrlFormatter() def add_line(self, line): self._lines.append(self._line_formatter.format(line)) def get_result(self): return '\n'.join(self._lines) class _HtmlFormatter(_Formatter): _hr_re = re.compile('^-{3,} *$') def __init__(self): self._result = _Formatted() self._table = _TableFormatter() self._line_formatter = _LineFormatter() def add_line(self, line): if self._add_table_row(line): return if self._table.is_started(): self._result.add(self._table.end(), join_after=False) if self._is_hr(line): self._result.add('<hr />\n', join_after=False) return self._result.add(self._line_formatter.format(line)) def _add_table_row(self, row): if self._table.is_table_row(row): self._table.add_row(row) return True return False def _is_hr(self, line): return bool(self._hr_re.match(line)) def get_result(self): if self._table.is_started(): self._result.add(self._table.end()) return self._result.get_result() class _Formatted(object): def __init__(self): self._result = [] self._joiner = '' def add(self, line, join_after=True): self._result.extend([self._joiner, line]) self._joiner = '\n' if join_after else '' def get_result(self): return ''.join(self._result) class _UrlFormatter(object): _formatting = False _image_exts = ('.jpg', '.jpeg', '.png', '.gif', '.bmp') _url = re.compile(''' ( (^|\ ) ["'([]* ) # begin of line or space and opt. any char "'([ (\w{3,9}://[\S]+?) # url (protocol is any alphanum 3-9 long string) (?= [])"'.,!?:;]* ($|\ ) ) # opt. any char ])"'.,!?:; and end of line or space ''', re.VERBOSE) def format(self, line): return self._format_url(line) def _format_url(self, line): return self._url.sub(self._repl_url, line) if ':' in line else line def _repl_url(self, match): pre = match.group(1) url = match.group(3).replace('"', '&quot;') if self._format_as_image(url): tmpl = '<img src="%s" title="%s" style="border: 1px solid gray" />' else: tmpl = '<a href="%s">%s</a>' return pre + tmpl % (url, url) def _format_as_image(self, url): return self._formatting and url.lower().endswith(self._image_exts) class _LineFormatter(_UrlFormatter): _formatting = True _bold = re.compile(''' ( # prefix (group 1) (^|\ ) # begin of line or space ["'(]* _? # optionally any char "'( and optional begin of italic ) # \* # start of bold ([^\ ].*?) # no space and then anything (group 3) \* # end of bold (?= # start of postfix (non-capturing group) _? ["').,!?:;]* # optional end of italic and any char "').,!?:; ($|\ ) # end of line or space ) ''', re.VERBOSE) _italic = re.compile(''' ( (^|\ ) ["'(]* ) # begin of line or space and opt. any char "'( _ # start of italic ([^\ _].*?) # no space or underline and then anything _ # end of italic (?= ["').,!?:;]* ($|\ ) ) # opt. any char "').,!?:; and end of line or space ''', re.VERBOSE) def format(self, line): return self._format_url(self._format_italic(self._format_bold(line))) def _format_bold(self, line): return self._bold.sub('\\1<b>\\3</b>', line) if '*' in line else line def _format_italic(self, line): return self._italic.sub('\\1<i>\\3</i>', line) if '_' in line else line class _TableFormatter(object): _is_table_line = re.compile('^\s*\| (.* |)\|\s*$') _line_splitter = re.compile(' \|(?= )') def __init__(self): self._rows = [] self._line_formatter = _LineFormatter() def is_table_row(self, row): return bool(self._is_table_line.match(row)) def is_started(self): return bool(self._rows) def add_row(self, text): text = text.strip()[1:-1] # remove outer whitespace and pipes cells = [cell.strip() for cell in self._line_splitter.split(text)] self._rows.append(cells) def end(self): ret = self._format_table(self._rows) self._rows = [] return ret def _format_table(self, rows): maxlen = max(len(row) for row in rows) table = ['<table border="1" class="doc">'] for row in rows: row += [''] * (maxlen - len(row)) # fix ragged tables table.append('<tr>') table.extend(['<td>%s</td>' % self._line_formatter.format(cell) for cell in row]) table.append('</tr>') table.append('</table>\n') return '\n'.join(table)
[ [ 1, 0, 0.0718, 0.0048, 0, 0.66, 0, 540, 0, 1, 0, 0, 540, 0, 0 ], [ 1, 0, 0.0813, 0.0048, 0, 0.66, 0.0909, 992, 0, 1, 0, 0, 992, 0, 0 ], [ 2, 0, 0.1053, 0.0239, 0, ...
[ "import re", "from unic import unic", "def html_escape(text, formatting=False):\n # TODO: Remove formatting attribute after RIDE does not use it anymore\n if formatting:\n return html_format(text)\n return _HtmlEscaper().format(text)", " if formatting:\n return html_format(text)", ...
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import sys import os from unic import unic def decode_output(string): """Decodes string from console encoding to Unicode.""" if _output_encoding: return unic(string, _output_encoding) return string def encode_output(string, errors='replace'): """Encodes string from Unicode to console encoding.""" # http://ironpython.codeplex.com/workitem/29487 if sys.platform == 'cli': return string return string.encode(_output_encoding, errors) def decode_from_file_system(string): """Decodes path from file system to Unicode.""" encoding = sys.getfilesystemencoding() if sys.platform.startswith('java'): # http://bugs.jython.org/issue1592 from java.lang import String string = String(string) return unic(string, encoding) if encoding else unic(string) def _get_output_encoding(): # Jython is buggy on Windows: http://bugs.jython.org/issue1568 if os.sep == '\\' and sys.platform.startswith('java'): return 'cp437' # Default DOS encoding encoding = _get_encoding_from_std_streams() if encoding: return encoding if os.sep == '/': return _read_encoding_from_unix_env() return 'cp437' # Default DOS encoding def _get_encoding_from_std_streams(): # Stream may not have encoding attribute if it is intercepted outside RF # in Python. Encoding is None if process's outputs are redirected. return getattr(sys.__stdout__, 'encoding', None) \ or getattr(sys.__stderr__, 'encoding', None) \ or getattr(sys.__stdin__, 'encoding', None) def _read_encoding_from_unix_env(): for name in 'LANG', 'LC_CTYPE', 'LANGUAGE', 'LC_ALL': try: # Encoding can be in format like `UTF-8` or `en_US.UTF-8` encoding = os.environ[name].split('.')[-1] 'testing that encoding is valid'.encode(encoding) except (KeyError, LookupError): pass else: return encoding return 'ascii' _output_encoding = _get_output_encoding()
[ [ 1, 0, 0.2027, 0.0135, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.2162, 0.0135, 0, 0.66, 0.1111, 688, 0, 1, 0, 0, 688, 0, 0 ], [ 1, 0, 0.2432, 0.0135, 0, ...
[ "import sys", "import os", "from unic import unic", "def decode_output(string):\n \"\"\"Decodes string from console encoding to Unicode.\"\"\"\n if _output_encoding:\n return unic(string, _output_encoding)\n return string", " \"\"\"Decodes string from console encoding to Unicode.\"\"\"", ...
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from java.io import FileOutputStream from javax.xml.transform.sax import SAXTransformerFactory from javax.xml.transform.stream import StreamResult from org.xml.sax.helpers import AttributesImpl from abstractxmlwriter import AbstractXmlWriter class XmlWriter(AbstractXmlWriter): def __init__(self, path): self.path = path self._output = FileOutputStream(path) self._writer = SAXTransformerFactory.newInstance().newTransformerHandler() self._writer.setResult(StreamResult(self._output)) self._writer.startDocument() self.content('\n') self.closed = False def _start(self, name, attrs): self._writer.startElement('', '', name, self._get_attrs_impl(attrs)) def _get_attrs_impl(self, attrs): ai = AttributesImpl() for name, value in attrs.items(): ai.addAttribute('', '', name, '', value) return ai def _content(self, content): self._writer.characters(content, 0, len(content)) def _end(self, name): self._writer.endElement('', '', name)
[ [ 1, 0, 0.3333, 0.0208, 0, 0.66, 0, 181, 0, 1, 0, 0, 181, 0, 0 ], [ 1, 0, 0.3542, 0.0208, 0, 0.66, 0.2, 576, 0, 1, 0, 0, 576, 0, 0 ], [ 1, 0, 0.375, 0.0208, 0, 0.66...
[ "from java.io import FileOutputStream", "from javax.xml.transform.sax import SAXTransformerFactory", "from javax.xml.transform.stream import StreamResult", "from org.xml.sax.helpers import AttributesImpl", "from abstractxmlwriter import AbstractXmlWriter", "class XmlWriter(AbstractXmlWriter):\n\n def _...
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os.path import sys import re import traceback from unic import unic from robot.errors import DataError, TimeoutError, RemoteError RERAISED_EXCEPTIONS = (KeyboardInterrupt, SystemExit, MemoryError) if sys.platform.startswith('java'): from java.io import StringWriter, PrintWriter from java.lang import Throwable, OutOfMemoryError RERAISED_EXCEPTIONS += (OutOfMemoryError,) _java_trace_re = re.compile('^\s+at (\w.+)') _ignored_java_trace = ('org.python.', 'robot.running.', 'robot$py.', 'sun.reflect.', 'java.lang.reflect.') _ignore_trace_until = (os.path.join('robot','running','handlers.py'), '<lambda>') _generic_exceptions = ('AssertionError', 'AssertionFailedError', 'Exception', 'Error', 'RuntimeError', 'RuntimeException', 'DataError', 'TimeoutError', 'RemoteError') def get_error_message(): """Returns error message of the last occurred exception. This method handles also exceptions containing unicode messages. Thus it MUST be used to get messages from all exceptions originating outside the framework. """ return ErrorDetails().message def get_error_details(): """Returns error message and details of the last occurred exception. """ dets = ErrorDetails() return dets.message, dets.traceback class ErrorDetails(object): """This class wraps the last occurred exception It has attributes message, traceback and error, where message contains type and message of the original error, traceback it's contains traceback (or stack trace in case of Java exception) and error contains the original error instance This class handles also exceptions containing unicode messages. Thus it MUST be used to get messages from all exceptions originating outside the framework. """ def __init__(self): exc_type, exc_value, exc_traceback = sys.exc_info() if exc_type in RERAISED_EXCEPTIONS: raise exc_value if _is_java_exception(exc_value): self.message = _get_java_message(exc_type, exc_value) self.traceback = _get_java_details(exc_value) else: self.message = _get_python_message(exc_type, exc_value) self.traceback = _get_python_details(exc_value, exc_traceback) self.error = exc_value def _is_java_exception(exc): return sys.platform.startswith('java') and isinstance(exc, Throwable) def _get_name(exc_type): try: return exc_type.__name__ except AttributeError: return unic(exc_type) def _get_java_message(exc_type, exc_value): exc_name = _get_name(exc_type) # OOME.getMessage and even toString seem to throw NullPointerException if exc_type is OutOfMemoryError: exc_msg = str(exc_value) else: exc_msg = exc_value.getMessage() return _format_message(exc_name, exc_msg, java=True) def _get_java_details(exc_value): # OOME.printStackTrace seems to throw NullPointerException if isinstance(exc_value, OutOfMemoryError): return '' output = StringWriter() exc_value.printStackTrace(PrintWriter(output)) lines = [ line for line in output.toString().splitlines() if line and not _is_ignored_stacktrace_line(line) ] details = '\n'.join(lines) msg = unic(exc_value.getMessage() or '') if msg: details = details.replace(msg, '', 1) return details def _is_ignored_stacktrace_line(line): res = _java_trace_re.match(line) if res is None: return False location = res.group(1) for entry in _ignored_java_trace: if location.startswith(entry): return True return False def _get_python_message(exc_type, exc_value): # If exception is a "string exception" without a message exc_value is None if exc_value is None: return unic(exc_type) name = _get_name(exc_type) try: msg = unicode(exc_value) except UnicodeError: # Happens if message is Unicode and version < 2.6 msg = ' '.join(unic(a) for a in exc_value.args) return _format_message(name, msg) def _get_python_details(exc_value, exc_tb): if isinstance(exc_value, (DataError, TimeoutError)): return '' if isinstance(exc_value, RemoteError): return exc_value.traceback tb = traceback.extract_tb(exc_tb) for row, (path, _, func, _) in enumerate(tb): if path.endswith(_ignore_trace_until[0]) and func == _ignore_trace_until[1]: tb = tb[row+1:] break details = 'Traceback (most recent call last):\n' \ + ''.join(traceback.format_list(tb)) return details.strip() def _format_message(name, message, java=False): message = unic(message or '') if java: message = _clean_up_java_message(message, name) name = name.split('.')[-1] # Use only last part of the name if message == '': return name if name in _generic_exceptions: return message return '%s: %s' % (name, message) def _clean_up_java_message(msg, name): # Remove possible stack trace from messages lines = msg.splitlines() while lines: if _java_trace_re.match(lines[-1]): lines.pop() else: break msg = '\n'.join(lines) # Remove possible exception name from the message tokens = msg.split(':', 1) if len(tokens) == 2 and tokens[0] == name: msg = tokens[1] return msg.strip()
[ [ 1, 0, 0.0894, 0.0056, 0, 0.66, 0, 79, 0, 1, 0, 0, 79, 0, 0 ], [ 1, 0, 0.095, 0.0056, 0, 0.66, 0.0435, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.1006, 0.0056, 0, 0.6...
[ "import os.path", "import sys", "import re", "import traceback", "from unic import unic", "from robot.errors import DataError, TimeoutError, RemoteError", "RERAISED_EXCEPTIONS = (KeyboardInterrupt, SystemExit, MemoryError)", "if sys.platform.startswith('java'):\n from java.io import StringWriter, P...
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from unic import unic _ILLEGAL_CHARS_IN_XML = u'\x00\x01\x02\x03\x04\x05\x06\x07\x08\x0b\x0c\x0e' \ + u'\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f\ufffe' class AbstractXmlWriter: def start(self, name, attributes={}, newline=True): self._start(name, self._escape_attrs(attributes)) if newline: self.content('\n') def _start(self, name, attrs): raise NotImplementedError def _escape_attrs(self, attrs): return dict((n, self._escape(v)) for n, v in attrs.items()) def _escape(self, content): content = unic(content) for char in _ILLEGAL_CHARS_IN_XML: # Avoid bug http://ironpython.codeplex.com/workitem/29402 if char in content: content = content.replace(char, '') return content def content(self, content): if content is not None: self._content(self._escape(content)) def _content(self, content): raise NotImplementedError def end(self, name, newline=True): self._end(name) if newline: self.content('\n') def _end(self, name): raise NotImplementedError def element(self, name, content=None, attributes={}, newline=True): self.start(name, attributes, newline=False) self.content(content) self.end(name, newline) def close(self): self._close() self.closed = True def _close(self): self._writer.endDocument() self._output.close()
[ [ 1, 0, 0.2174, 0.0145, 0, 0.66, 0, 992, 0, 1, 0, 0, 992, 0, 0 ], [ 14, 0, 0.2681, 0.029, 0, 0.66, 0.5, 484, 4, 0, 0, 0, 0, 0, 0 ], [ 3, 0, 0.6594, 0.6957, 0, 0.66,...
[ "from unic import unic", "_ILLEGAL_CHARS_IN_XML = u'\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\x0b\\x0c\\x0e' \\\n + u'\\x0f\\x10\\x11\\x12\\x13\\x14\\x15\\x16\\x17\\x18\\x19\\x1a\\x1b\\x1c\\x1d\\x1e\\x1f\\ufffe'", "class AbstractXmlWriter:\n\n def start(self, name, attributes={}, newline=True):\n ...
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import sys import inspect from robot.errors import DataError from error import get_error_message, get_error_details from robotpath import normpath, abspath def simple_import(path_to_module): err_prefix = "Importing '%s' failed: " % path_to_module if not os.path.exists(path_to_module): raise DataError(err_prefix + 'File does not exist') try: return _import_module_by_path(path_to_module) except: raise DataError(err_prefix + get_error_message()) def _import_module_by_path(path): moddir, modname = _split_path_to_module(path) sys.path.insert(0, moddir) try: module = __import__(modname) if hasattr(module, '__file__'): impdir = os.path.dirname(module.__file__) if normpath(impdir) != normpath(moddir): del sys.modules[modname] module = __import__(modname) return module finally: sys.path.pop(0) def _split_path_to_module(path): moddir, modfile = os.path.split(abspath(path)) modname = os.path.splitext(modfile)[0] return moddir, modname def import_(name, type_='test library'): """Imports Python class/module or Java class with given name. 'name' can also be a path to the library and in that case the directory containing the lib is automatically put into sys.path and removed there afterwards. 'type_' is used in error message if importing fails. Class can either live in a module/package or be 'standalone'. In the former case tha name is something like 'MyClass' and in the latter it could be 'your.package.YourLibrary'). Python classes always live in a module but if the module name is exactly same as the class name the former also works in Python. Example: If you have a Python class 'MyLibrary' in a module 'mymodule' it must be imported with name 'mymodule.MyLibrary'. If the name of the module is also 'MyLibrary' then it is possible to use only name 'MyLibrary'. """ if '.' not in name or os.path.exists(name): code, module = _non_dotted_import(name, type_) else: code, module = _dotted_import(name, type_) source = _get_module_source(module) return code, source def _non_dotted_import(name, type_): try: if os.path.exists(name): module = _import_module_by_path(name) else: module = __import__(name) except: _raise_import_failed(type_, name) try: code = getattr(module, module.__name__) if not inspect.isclass(code): raise AttributeError except AttributeError: code = module return code, module def _dotted_import(name, type_): parentname, libname = name.rsplit('.', 1) try: try: module = __import__(parentname, fromlist=[str(libname)]) except ImportError: # Hack to support standalone Jython: # http://code.google.com/p/robotframework/issues/detail?id=515 if not sys.platform.startswith('java'): raise __import__(name) module = __import__(parentname, fromlist=[str(libname)]) except: _raise_import_failed(type_, name) try: code = getattr(module, libname) except AttributeError: _raise_no_lib_in_module(type_, parentname, libname) if not (inspect.ismodule(code) or inspect.isclass(code)): _raise_invalid_type(type_, code) return code, module def _get_module_source(module): source = getattr(module, '__file__', None) return abspath(source) if source else '<unknown>' def _raise_import_failed(type_, name): error_msg, error_details = get_error_details() msg = ["Importing %s '%s' failed: %s" % (type_, name, error_msg), "PYTHONPATH: %s" % sys.path, error_details] if sys.platform.startswith('java'): from java.lang import System msg.insert(-1, 'CLASSPATH: %s' % System.getProperty('java.class.path')) raise DataError('\n'.join(msg)) def _raise_no_lib_in_module(type_, modname, libname): raise DataError("%s module '%s' does not contain '%s'." % (type_.capitalize(), modname, libname)) def _raise_invalid_type(type_, code): raise DataError("Imported %s should be a class or module, got %s." % (type_, type(code).__name__))
[ [ 1, 0, 0.1087, 0.0072, 0, 0.66, 0, 688, 0, 1, 0, 0, 688, 0, 0 ], [ 1, 0, 0.1159, 0.0072, 0, 0.66, 0.0667, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.1232, 0.0072, 0, ...
[ "import os", "import sys", "import inspect", "from robot.errors import DataError", "from error import get_error_message, get_error_details", "from robotpath import normpath, abspath", "def simple_import(path_to_module):\n err_prefix = \"Importing '%s' failed: \" % path_to_module\n if not os.path.e...
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import urllib from encoding import decode_from_file_system if os.sep == '\\': _CASE_INSENSITIVE_FILESYSTEM = True else: try: _CASE_INSENSITIVE_FILESYSTEM = os.listdir('/tmp') == os.listdir('/TMP') except OSError: _CASE_INSENSITIVE_FILESYSTEM = False def normpath(path): """Returns path in normalized and absolute format. On case-insensitive file systems the path is also case normalized. If that is not desired, abspath should be used instead. """ path = abspath(path) if _CASE_INSENSITIVE_FILESYSTEM: path = path.lower() return path def abspath(path): """Replacement for os.path.abspath with some bug fixes and enhancements. 1) Converts non-Unicode paths to Unicode using file system encoding 2) At least Jython 2.5.1 on Windows returns wrong path with 'c:'. 3) Python until 2.6.5 and at least Jython 2.5.1 don't handle non-ASCII characters in the working directory: http://bugs.python.org/issue3426 """ if not isinstance(path, unicode): path = decode_from_file_system(path) if os.sep == '\\' and len(path) == 2 and path[1] == ':': return path + '\\' return os.path.normpath(os.path.join(os.getcwdu(), path)) def get_link_path(target, base): """Returns a relative path to a target from a base. If base is an existing file, then its parent directory is considered. Otherwise, base is assumed to be a directory. Rationale: os.path.relpath is not available before Python 2.6 """ pathname = _get_pathname(target, base) url = urllib.pathname2url(pathname.encode('UTF-8')) if os.path.isabs(pathname): pre = url.startswith('/') and 'file:' or 'file:///' url = pre + url # Want consistent url on all platforms/interpreters return url.replace('%5C', '/').replace('%3A', ':').replace('|', ':') def _get_pathname(target, base): target = abspath(target) base = abspath(base) if os.path.isfile(base): base = os.path.dirname(base) if base == target: return os.path.basename(target) base_drive, base_path = os.path.splitdrive(base) # if in Windows and base and link on different drives if os.path.splitdrive(target)[0] != base_drive: return target common_len = len(_common_path(base, target)) if base_path == os.sep: return target[common_len:] if common_len == len(base_drive) + len(os.sep): common_len -= len(os.sep) dirs_up = os.sep.join([os.pardir] * base[common_len:].count(os.sep)) return os.path.join(dirs_up, target[common_len + len(os.sep):]) def _common_path(p1, p2): """Returns the longest path common to p1 and p2. Rationale: as os.path.commonprefix is character based, it doesn't consider path separators as such, so it may return invalid paths: commonprefix(('/foo/bar/', '/foo/baz.txt')) -> '/foo/ba' (instead of /foo) """ while p1 and p2: if p1 == p2: return p1 if len(p1) > len(p2): p1 = os.path.dirname(p1) else: p2 = os.path.dirname(p2) return ''
[ [ 1, 0, 0.1415, 0.0094, 0, 0.66, 0, 688, 0, 1, 0, 0, 688, 0, 0 ], [ 1, 0, 0.1509, 0.0094, 0, 0.66, 0.125, 614, 0, 1, 0, 0, 614, 0, 0 ], [ 1, 0, 0.1698, 0.0094, 0, 0...
[ "import os", "import urllib", "from encoding import decode_from_file_system", "if os.sep == '\\\\':\n _CASE_INSENSITIVE_FILESYSTEM = True\nelse:\n try:\n _CASE_INSENSITIVE_FILESYSTEM = os.listdir('/tmp') == os.listdir('/TMP')\n except OSError:\n _CASE_INSENSITIVE_FILESYSTEM = False", ...
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from abstractxmlwriter import AbstractXmlWriter from htmlutils import html_escape, html_attr_escape from unic import unic class HtmlWriter(AbstractXmlWriter): def __init__(self, output): """'output' is an open file object. Given 'output' must have been opened in 'wb' mode to be able to write into it with UTF-8 encoding. """ self.output = output def start(self, name, attrs=None, newline=True): self._start(name, attrs, newline=newline) def start_and_end(self, name, attrs=None, newline=True): self._start(name, attrs, close=True, newline=newline) def content(self, content=None, escape=True): """Given content doesn't need to be a string""" if content is not None: if escape: content = html_escape(unic(content)) self._write(content) def end(self, name, newline=True): self._write('</%s>%s' % (name, '\n' if newline else '')) def element(self, name, content=None, attrs=None, escape=True, newline=True): self.start(name, attrs, newline=False) self.content(content, escape) self.end(name, newline) def start_many(self, names, newline=True): for name in names: self.start(name, newline=newline) def end_many(self, names, newline=True): for name in names: self.end(name, newline) def _start(self, name, attrs, close=False, newline=True): self._write('<%s%s%s>%s' % (name, self._get_attrs(attrs), ' /' if close else '', '\n' if newline else '')) def _get_attrs(self, attrs): if not attrs: return '' return ' ' + ' '.join('%s="%s"' % (name, html_attr_escape(attrs[name])) for name in sorted(attrs)) def _write(self, text): self.output.write(text.encode('UTF-8'))
[ [ 1, 0, 0.2083, 0.0139, 0, 0.66, 0, 993, 0, 1, 0, 0, 993, 0, 0 ], [ 1, 0, 0.2222, 0.0139, 0, 0.66, 0.3333, 801, 0, 2, 0, 0, 801, 0, 0 ], [ 1, 0, 0.2361, 0.0139, 0, ...
[ "from abstractxmlwriter import AbstractXmlWriter", "from htmlutils import html_escape, html_attr_escape", "from unic import unic", "class HtmlWriter(AbstractXmlWriter):\n\n def __init__(self, output):\n \"\"\"'output' is an open file object.\n\n Given 'output' must have been opened in 'wb' mo...
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from unic import unic from misc import seq2str2 from charwidth import get_char_width _MAX_ASSIGN_LENGTH = 200 _MAX_ERROR_LINES = 40 _MAX_ERROR_LINE_LENGTH = 78 _ERROR_CUT_EXPLN = (' [ Message content over the limit has been removed. ]') def cut_long_message(msg): lines = msg.splitlines() lengths = _count_line_lenghts(lines) if sum(lengths) <= _MAX_ERROR_LINES: return msg start = _prune_excess_lines(lines, lengths) end = _prune_excess_lines(lines, lengths, True) return '\n'.join(start + [_ERROR_CUT_EXPLN] + end) def _prune_excess_lines(lines, lengths, from_end=False): if from_end: lines.reverse() lengths.reverse() ret = [] total = 0 limit = _MAX_ERROR_LINES/2 for line, length in zip(lines[:limit], lengths[:limit]): if total + length >= limit: ret.append(_cut_long_line(line, total, from_end)) break total += length ret.append(line) if from_end: ret.reverse() return ret def _cut_long_line(line, used, from_end): available_lines = _MAX_ERROR_LINES/2 - used available_chars = available_lines * _MAX_ERROR_LINE_LENGTH - 3 if len(line) > available_chars: if not from_end: line = line[:available_chars] + '...' else: line = '...' + line[-available_chars:] return line def _count_line_lenghts(lines): return [ _count_virtual_line_length(line) for line in lines ] def _count_virtual_line_length(line): length = len(line) / _MAX_ERROR_LINE_LENGTH if not len(line) % _MAX_ERROR_LINE_LENGTH == 0 or len(line) == 0: length += 1 return length def format_assign_message(variable, value, cut_long=True): value = unic(value) if variable.startswith('$') else seq2str2(value) if cut_long and len(value) > _MAX_ASSIGN_LENGTH: value = value[:_MAX_ASSIGN_LENGTH] + '...' return '%s = %s' % (variable, value) def get_console_length(text): return sum(get_char_width(char) for char in text) def pad_console_length(text, width, cut_left=False): if width < 5: width = 5 diff = get_console_length(text) - width if diff <= 0: return _pad_width(text, width) if cut_left: return _pad_width('...'+_lose_width_left(text, diff+3), width) return _pad_width(_lose_width_right(text, diff+3)+'...', width) def _pad_width(text, width): more = width - get_console_length(text) return text + ' ' * more def _lose_width_right(text, diff): return _lose_width(text, diff, -1, slice(None, -1)) def _lose_width_left(text, diff): return _lose_width(text, diff, 0, slice(1, None)) def _lose_width(text, diff, index, slice): lost = 0 while lost < diff: lost += get_console_length(text[index]) text = text[slice] return text
[ [ 1, 0, 0.1389, 0.0093, 0, 0.66, 0, 992, 0, 1, 0, 0, 992, 0, 0 ], [ 1, 0, 0.1481, 0.0093, 0, 0.66, 0.0556, 733, 0, 1, 0, 0, 733, 0, 0 ], [ 1, 0, 0.1574, 0.0093, 0, ...
[ "from unic import unic", "from misc import seq2str2", "from charwidth import get_char_width", "_MAX_ASSIGN_LENGTH = 200", "_MAX_ERROR_LINES = 40", "_MAX_ERROR_LINE_LENGTH = 78", "_ERROR_CUT_EXPLN = (' [ Message content over the limit has been removed. ]')", "def cut_long_message(msg):\n lines = ...
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import sys from StringIO import StringIO try: import xml.etree.cElementTree as ET except ImportError: try: import cElementTree as ET except ImportError: try: import xml.etree.ElementTree as ET # Raises ImportError due to missing expat on IronPython by default ET.parse(StringIO('<test/>')) except ImportError: try: import elementtree.ElementTree as ET except ImportError: raise ImportError('No valid ElementTree XML parser module found') def get_root(path, string=None, node=None): # This should NOT be changed to 'if not node:'. See chapter Truth Testing # from http://effbot.org/zone/element.htm#the-element-type if node is not None: return node source = _get_source(path, string) try: return ET.parse(source).getroot() finally: if hasattr(source, 'close'): source.close() def _get_source(path, string): if not path: return StringIO(string) # ElementTree 1.2.7 preview (first ET with IronPython support) doesn't # handler non-ASCII chars correctly if an open file given to it. if sys.platform == 'cli': return path # ET.parse doesn't close files it opens, which causes serious problems # with Jython 2.5(.1) on Windows: http://bugs.jython.org/issue1598 return open(path, 'rb')
[ [ 1, 0, 0.2727, 0.0182, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.2909, 0.0182, 0, 0.66, 0.25, 609, 0, 1, 0, 0, 609, 0, 0 ], [ 7, 0, 0.4364, 0.2727, 0, 0....
[ "import sys", "from StringIO import StringIO", "try:\n import xml.etree.cElementTree as ET\nexcept ImportError:\n try:\n import cElementTree as ET\n except ImportError:\n try:\n import xml.etree.ElementTree as ET", " import xml.etree.cElementTree as ET", " try:\n ...
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os from abstractxmlwriter import AbstractXmlWriter def XmlWriter(path): if path == 'NONE': return FakeXMLWriter() if os.name == 'java': from jyxmlwriter import XmlWriter else: from pyxmlwriter import XmlWriter return XmlWriter(path) class FakeXMLWriter(AbstractXmlWriter): closed = False _start = _content = _end = _close = lambda self, *args: None
[ [ 1, 0, 0.4688, 0.0312, 0, 0.66, 0, 688, 0, 1, 0, 0, 688, 0, 0 ], [ 1, 0, 0.5312, 0.0312, 0, 0.66, 0.3333, 993, 0, 1, 0, 0, 993, 0, 0 ], [ 2, 0, 0.7344, 0.25, 0, 0....
[ "import os", "from abstractxmlwriter import AbstractXmlWriter", "def XmlWriter(path):\n if path == 'NONE':\n return FakeXMLWriter()\n if os.name == 'java':\n from jyxmlwriter import XmlWriter\n else:\n from pyxmlwriter import XmlWriter\n return XmlWriter(path)", " if path =...
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import time from normalizing import normalize from misc import plural_or_not def _get_timetuple(epoch_secs=None): if _CURRENT_TIME: return _CURRENT_TIME if epoch_secs is None: # can also be 0 (at least in unit tests) epoch_secs = time.time() secs, millis = _float_secs_to_secs_and_millis(epoch_secs) timetuple = time.localtime(secs)[:6] # from year to secs return timetuple + (millis,) def _float_secs_to_secs_and_millis(secs): isecs = int(secs) millis = int(round((secs - isecs) * 1000)) return (isecs, millis) if millis < 1000 else (isecs+1, 0) _CURRENT_TIME = None # Seam for mocking time-dependent tests START_TIME = _get_timetuple() def timestr_to_secs(timestr): """Parses time in format like '1h 10s' and returns time in seconds (float). Given time must be in format '1d 2h 3m 4s 5ms' with following rules. - Time parts having zero value can be ignored (e.g. '3m 4s' is ok) - Format is case and space insensitive - Instead of 'd' it is also possible to use 'day' or 'days' - Instead of 'h' also 'hour' and 'hours' are ok - Instead of 'm' also 'minute', 'minutes', 'min' and 'mins' are ok - Instead of 's' also 'second', 'seconds', 'sec' and 'secs' are ok - Instead of 'ms' also 'millisecond', 'milliseconds' and 'millis' are ok - It is possible to give time only as a float and then it is considered to be seconds (e.g. '123', '123.0', '123s', '2min 3s' are all equivelant) """ try: secs = _timestr_to_secs(timestr) except (ValueError, TypeError): raise ValueError("Invalid time string '%s'" % timestr) return round(secs, 3) def _timestr_to_secs(timestr): timestr = _normalize_timestr(timestr) if timestr == '': raise ValueError try: return float(timestr) except ValueError: pass millis = secs = mins = hours = days = 0 if timestr[0] == '-': sign = -1 timestr = timestr[1:] else: sign = 1 temp = [] for c in timestr: if c == 'x': millis = float(''.join(temp)); temp = [] elif c == 's': secs = float(''.join(temp)); temp = [] elif c == 'm': mins = float(''.join(temp)); temp = [] elif c == 'h': hours = float(''.join(temp)); temp = [] elif c == 'p': days = float(''.join(temp)); temp = [] else: temp.append(c) if temp: raise ValueError return sign * (millis/1000 + secs + mins*60 + hours*60*60 + days*60*60*24) def _normalize_timestr(timestr): if isinstance(timestr, (int, long, float)): return timestr timestr = normalize(timestr) for item in 'milliseconds', 'millisecond', 'millis': timestr = timestr.replace(item, 'ms') for item in 'seconds', 'second', 'secs', 'sec': timestr = timestr.replace(item, 's') for item in 'minutes', 'minute', 'mins', 'min': timestr = timestr.replace(item, 'm') for item in 'hours', 'hour': timestr = timestr.replace(item, 'h') for item in 'days', 'day': timestr = timestr.replace(item, 'd') # 1) 'ms' -> 'x' to ease processing later # 2) 'd' -> 'p' because float('1d') returns 1.0 in Jython (bug submitted) return timestr.replace('ms','x').replace('d','p') def secs_to_timestr(secs, compact=False): """Converts time in seconds to a string representation. Returned string is in format like '1 day 2 hours 3 minutes 4 seconds 5 milliseconds' with following rules. - Time parts having zero value are not included (e.g. '3 minutes 4 seconds' instead of '0 days 0 hours 3 minutes 4 seconds') - Hour part has a maximun of 23 and minutes and seconds both have 59 (e.g. '1 minute 40 seconds' instead of '100 seconds') If compact has value 'True', short suffixes are used. (e.g. 1d 2h 3min 4s 5ms) """ return _SecsToTimestrHelper(secs, compact).get_value() class _SecsToTimestrHelper: def __init__(self, float_secs, compact): self._compact = compact self._ret = [] self._sign, millis, secs, mins, hours, days \ = self._secs_to_components(float_secs) self._add_item(days, 'd', 'day') self._add_item(hours, 'h', 'hour') self._add_item(mins, 'min', 'minute') self._add_item(secs, 's', 'second') self._add_item(millis, 'ms', 'millisecond') def get_value(self): if len(self._ret) > 0: return self._sign + ' '.join(self._ret) return '0s' if self._compact else '0 seconds' def _add_item(self, value, compact_suffix, long_suffix): if value == 0: return if self._compact: suffix = compact_suffix else: suffix = ' %s%s' % (long_suffix, plural_or_not(value)) self._ret.append('%d%s' % (value, suffix)) def _secs_to_components(self, float_secs): if float_secs < 0: sign = '- ' float_secs = abs(float_secs) else: sign = '' int_secs, millis = _float_secs_to_secs_and_millis(float_secs) secs = int_secs % 60 mins = int(int_secs / 60) % 60 hours = int(int_secs / (60*60)) % 24 days = int(int_secs / (60*60*24)) return sign, millis, secs, mins, hours, days def format_time(timetuple_or_epochsecs, daysep='', daytimesep=' ', timesep=':', millissep=None, gmtsep=None): """Returns a timestamp formatted from given time using separators. Time can be given either as a timetuple or seconds after epoch. Timetuple is (year, month, day, hour, min, sec[, millis]), where parts must be integers and millis is required only when millissep is not None. Notice that this is not 100% compatible with standard Python timetuples which do not have millis. Seconds after epoch can be either an integer or a float. """ if isinstance(timetuple_or_epochsecs, (int, long, float)): timetuple = _get_timetuple(timetuple_or_epochsecs) else: timetuple = timetuple_or_epochsecs daytimeparts = ['%02d' % t for t in timetuple[:6]] day = daysep.join(daytimeparts[:3]) time_ = timesep.join(daytimeparts[3:6]) millis = millissep and '%s%03d' % (millissep, timetuple[6]) or '' return day + daytimesep + time_ + millis + _diff_to_gmt(gmtsep) def _diff_to_gmt(sep): if not sep: return '' if time.altzone == 0: sign = '' elif time.altzone > 0: sign = '-' else: sign = '+' minutes = abs(time.altzone) / 60.0 hours, minutes = divmod(minutes, 60) return '%sGMT%s%s%02d:%02d' % (sep, sep, sign, hours, minutes) def get_time(format='timestamp', time_=None): """Return the given or current time in requested format. If time is not given, current time is used. How time is returned is is deternined based on the given 'format' string as follows. Note that all checks are case insensitive. - If 'format' contains word 'epoch' the time is returned in seconds after the unix epoch. - If 'format' contains any of the words 'year', 'month', 'day', 'hour', 'min' or 'sec' only selected parts are returned. The order of the returned parts is always the one in previous sentence and order of words in 'format' is not significant. Parts are returned as zero padded strings (e.g. May -> '05'). - Otherwise (and by default) the time is returned as a timestamp string in format '2006-02-24 15:08:31' """ if time_ is None: time_ = time.time() format = format.lower() # 1) Return time in seconds since epoc if 'epoch' in format: return int(time_) timetuple = time.localtime(time_) parts = [] for i, match in enumerate('year month day hour min sec'.split()): if match in format: parts.append('%.2d' % timetuple[i]) # 2) Return time as timestamp if not parts: return format_time(timetuple, daysep='-') # Return requested parts of the time elif len(parts) == 1: return parts[0] else: return parts def parse_time(timestr): """Parses the time string and returns its value as seconds since epoch. Time can be given in four different formats: 1) Numbers are interpreted as time since epoch directly. It is possible to use also ints and floats, not only strings containing numbers. 2) Valid timestamp ('YYYY-MM-DD hh:mm:ss' and 'YYYYMMDD hhmmss'). 3) 'NOW' (case-insensitive) is the current time rounded down to the closest second. 4) Format 'NOW - 1 day' or 'NOW + 1 hour 30 min' is the current time plus/minus the time specified with the time string. """ try: ret = int(timestr) except ValueError: pass else: if ret < 0: raise ValueError("Epoch time must be positive (got %s)" % timestr) return ret try: return timestamp_to_secs(timestr, (' ', ':', '-', '.')) except ValueError: pass normtime = timestr.lower().replace(' ', '') now = int(time.time()) if normtime == 'now': return now if normtime.startswith('now'): if normtime[3] == '+': return now + timestr_to_secs(normtime[4:]) if normtime[3] == '-': return now - timestr_to_secs(normtime[4:]) raise ValueError("Invalid time format '%s'" % timestr) def get_timestamp(daysep='', daytimesep=' ', timesep=':', millissep='.'): return format_time(_get_timetuple(), daysep, daytimesep, timesep, millissep) def timestamp_to_secs(timestamp, seps=('', ' ', ':', '.'), millis=False): try: secs = _timestamp_to_millis(timestamp, seps) / 1000.0 except (ValueError, OverflowError): raise ValueError("Invalid timestamp '%s'" % timestamp) if millis: return round(secs, 3) return int(round(secs)) def secs_to_timestamp(secs, seps=None, millis=False): if not seps: seps = ('', ' ', ':', '.' if millis else None) ttuple = time.localtime(secs)[:6] if millis: millis = (secs - int(secs)) * 1000 ttuple = ttuple + (int(millis),) return format_time(ttuple, *seps) def get_start_timestamp(daysep='', daytimesep=' ', timesep=':', millissep=None): return format_time(START_TIME, daysep, daytimesep, timesep, millissep) def get_elapsed_time(start_time, end_time=None, seps=('', ' ', ':', '.')): """Returns the time between given timestamps in milliseconds. If 'end_time' is not given current timestamp is got with get_timestamp using given 'seps'. 'seps' is a tuple containing 'daysep', 'daytimesep', 'timesep' and 'millissep' used in given timestamps. """ if start_time == 'N/A' or end_time == 'N/A': return 0 if not end_time: end_time = get_timestamp(*seps) start_millis = _timestamp_to_millis(start_time, seps) end_millis = _timestamp_to_millis(end_time, seps) # start/end_millis can be long but we want to return int when possible return int(end_millis - start_millis) def elapsed_time_to_string(elapsed_millis): """Converts elapsed time in millisecods to format 'hh:mm:ss.mil'""" elapsed_millis = round(elapsed_millis) if elapsed_millis < 0: pre = '-' elapsed_millis = abs(elapsed_millis) else: pre = '' millis = elapsed_millis % 1000 secs = int(elapsed_millis / 1000) % 60 mins = int(elapsed_millis / 60000) % 60 hours = int(elapsed_millis / 3600000) return '%s%02d:%02d:%02d.%03d' % (pre, hours, mins, secs, millis) def _timestamp_to_millis(timestamp, seps): Y, M, D, h, m, s, millis = _split_timestamp(timestamp, seps) secs = time.mktime((Y, M, D, h, m, s, 0, 0, time.daylight)) return int(round(1000*secs + millis)) def _split_timestamp(timestamp, seps): for sep in seps: if sep: timestamp = timestamp.replace(sep, '') timestamp = timestamp.ljust(17, '0') years = int(timestamp[:4]) mons = int(timestamp[4:6]) days = int(timestamp[6:8]) hours = int(timestamp[8:10]) mins = int(timestamp[10:12]) secs = int(timestamp[12:14]) millis = int(timestamp[14:17]) return years, mons, days, hours, mins, secs, millis
[ [ 1, 0, 0.0426, 0.0028, 0, 0.66, 0, 654, 0, 1, 0, 0, 654, 0, 0 ], [ 1, 0, 0.0483, 0.0028, 0, 0.66, 0.0435, 901, 0, 1, 0, 0, 901, 0, 0 ], [ 1, 0, 0.0511, 0.0028, 0, ...
[ "import time", "from normalizing import normalize", "from misc import plural_or_not", "def _get_timetuple(epoch_secs=None):\n if _CURRENT_TIME:\n return _CURRENT_TIME\n if epoch_secs is None: # can also be 0 (at least in unit tests)\n epoch_secs = time.time()\n secs, millis = _float_se...
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os.path from robot.variables import Variables from robot.errors import DataError, FrameworkError from robot import utils PRE = '<!-- ' POST = ' -->' class Namespace(Variables): def __init__(self, **kwargs): Variables.__init__(self, ['$']) for key, value in kwargs.items(): self['${%s}' % key] = value class Template: def __init__(self, path=None, template=None, functions=None): if path is None and template is None: raise FrameworkError("Either 'path' or 'template' must be given") if template is None: tfile = open(path) template = tfile.read() tfile.close() self.parent_dir = os.path.dirname(utils.abspath(path)) else: self.parent_dir = None self._template = template self._functions = functions or utils.NormalizedDict() # True means handlers for more than single line self._handlers = { 'INCLUDE': (self._handle_include, False), 'IMPORT': (self._handle_import, False), 'CALL': (self._handle_call, False), 'IF': (self._handle_if, True), 'FOR': (self._handle_for, True), 'FUNCTION': (self._handle_function, True) } def generate(self, namespace, output=None): self._namespace = namespace return self._process(self._template, output) def _process(self, template, output=None): result = Result(output) lines = template.splitlines() while lines: line = lines.pop(0) try: result.add(self._process_line(line.strip(), lines)) except ValueError: result.add(self._handle_variables(line)) return result.get_result() def _process_line(self, line, lines): if not line.startswith(PRE) and line.endswith(POST): raise ValueError name, expression = line[len(PRE):-len(POST)].split(' ', 1) try: handler, multiline = self._handlers[name] except KeyError: raise ValueError if multiline: block_lines = self._get_multi_line_block(name, lines) return handler(expression, block_lines) return handler(expression) def _get_multi_line_block(self, name, lines): """Returns string containing lines before END matching given name. Removes the returned lines from given 'lines'. """ block_lines = [] endline = '%sEND %s%s' % (PRE, name, POST) while True: try: line = lines.pop(0) except IndexError: raise DataError('Invalid template: No END for %s' % name) if line.strip() == endline: break block_lines.append(line) return block_lines def _handle_variables(self, template): return self._namespace.replace_string(template) def _handle_include(self, path): included_file = open(self._get_full_path(path)) include = included_file.read() included_file.close() return self._handle_variables(include) def _handle_import(self, path): imported_file = open(self._get_full_path(path)) self._process(imported_file.read()) imported_file.close() return None def _handle_for(self, expression, block_lines): block = '\n'.join(block_lines) result = [] var_name, _, value_list = expression.split(' ', 2) namespace = self._namespace.copy() for value in namespace.replace_scalar(value_list): namespace[var_name] = value temp = Template(template=block, functions=self._functions) ret = temp.generate(namespace) if ret: result.append(ret) if not result: return None return '\n'.join(result) def _handle_if(self, expression, block_lines): expression = self._handle_variables(expression) if_block, else_block = self._get_if_and_else_blocks(block_lines) result = eval(expression) and if_block or else_block if not result: return None return self._process('\n'.join(result)) def _get_if_and_else_blocks(self, block_lines): else_line = PRE + 'ELSE' + POST if_block = [] else_block = [] block = if_block for line in block_lines: if line.strip() == else_line: block = else_block else: block.append(line) return if_block, else_block def _handle_call(self, expression): func_tokens = expression.split() name = func_tokens[0] args = func_tokens[1:] namespace = self._namespace.copy() try: func_args, func_body = self._functions[name] except KeyError: raise DataError("Non-existing function '%s', available: %s" % (name, self._functions.keys())) for key, value in zip(func_args, args): namespace[key] = namespace.replace_string(value) temp = Template(template=func_body, functions=self._functions) return temp.generate(namespace) def _handle_function(self, signature, block_lines): signature_tokens = signature.split() name = signature_tokens[0] args = signature_tokens[1:] self._functions[name] = (args, '\n'.join(block_lines)) def _get_full_path(self, path): if self.parent_dir is None: raise FrameworkError('Parent directory is None. Probably template ' 'was string and other files was referred. ' 'That is not supported.') abs_path = os.path.join(self.parent_dir, path) if os.path.exists(abs_path): return abs_path else: raise DataError("File '%s' does not exist." % abs_path) class Result: def __init__(self, output=None): self._output = output self._result = [] def add(self, text): if text is not None: if self._output is None: self._result.append(text) else: self._output.write(text.encode('UTF-8') + '\n') def get_result(self): if not self._result: return None return '\n'.join(self._result)
[ [ 1, 0, 0.0796, 0.005, 0, 0.66, 0, 79, 0, 1, 0, 0, 79, 0, 0 ], [ 1, 0, 0.0896, 0.005, 0, 0.66, 0.125, 595, 0, 1, 0, 0, 595, 0, 0 ], [ 1, 0, 0.0945, 0.005, 0, 0.66, ...
[ "import os.path", "from robot.variables import Variables", "from robot.errors import DataError, FrameworkError", "from robot import utils", "PRE = '<!-- '", "POST = ' -->'", "class Namespace(Variables):\n\n def __init__(self, **kwargs):\n Variables.__init__(self, ['$'])\n for key, value...
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import re _ESCAPE_RE = re.compile(r'(\\+)([^\\]{0,2})') # escapes and nextchars _SEQS_TO_BE_ESCAPED = ('\\', '${', '@{', '%{', '&{', '*{' , '=') def escape(item): if not isinstance(item, basestring): return item for seq in _SEQS_TO_BE_ESCAPED: item = item.replace(seq, '\\' + seq) return item def unescape(item): if not isinstance(item, basestring): return item result = [] unprocessed = item while True: res = _ESCAPE_RE.search(unprocessed) # If no escapes found append string to result and exit loop if res is None: result.append(unprocessed) break # Split string to pre match, escapes, nextchars and unprocessed parts # (e.g. '<pre><esc><nc><unproc>') where nextchars contains 0-2 chars # and unprocessed may contain more escapes. Pre match part contains # no escapes can is appended directly to result. result.append(unprocessed[:res.start()]) escapes = res.group(1) nextchars = res.group(2) unprocessed = unprocessed[res.end():] # Append every second escape char to result result.append('\\' * (len(escapes) / 2)) # Handle '\n', '\r' and '\t'. Note that both '\n' and '\n ' are # converted to '\n' if len(escapes) % 2 == 0 or len(nextchars) == 0 \ or nextchars[0] not in ['n','r','t']: result.append(nextchars) elif nextchars[0] == 'n': if len(nextchars) == 1 or nextchars[1] == ' ': result.append('\n') else: result.append('\n' + nextchars[1]) elif nextchars[0] == 'r': result.append('\r' + nextchars[1:]) else: result.append('\t' + nextchars[1:]) return ''.join(result)
[ [ 1, 0, 0.2308, 0.0154, 0, 0.66, 0, 540, 0, 1, 0, 0, 540, 0, 0 ], [ 14, 0, 0.2769, 0.0154, 0, 0.66, 0.25, 44, 3, 1, 0, 0, 821, 10, 1 ], [ 14, 0, 0.2923, 0.0154, 0, ...
[ "import re", "_ESCAPE_RE = re.compile(r'(\\\\+)([^\\\\]{0,2})') # escapes and nextchars", "_SEQS_TO_BE_ESCAPED = ('\\\\', '${', '@{', '%{', '&{', '*{' , '=')", "def escape(item):\n if not isinstance(item, basestring):\n return item\n for seq in _SEQS_TO_BE_ESCAPED:\n item = item.replace(...
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import etreewrapper class DomWrapper(object): def __init__(self, path=None, string=None, node=None): """Initialize by giving 'path' to an xml file or xml as a 'string'. Alternative initialization by giving dom 'node' ment to be used only internally. 'path' may actually also be an already opened file object (or anything accepted by ElementTree.parse). """ node = etreewrapper.get_root(path, string, node) self.source = path self.name = node.tag self.attrs = dict(node.items()) self.text = node.text or '' self.children = [DomWrapper(path, node=child) for child in list(node)] def get_nodes(self, path): """Returns a list of descendants matching given 'path'. Path must be a string in format 'child_name/grandchild_name/etc'. No slash is allowed at the beginning or end of the path string. Returns an empty list if no matching descendants found and raises AttributeError if path is invalid. """ if not isinstance(path, basestring) \ or path == '' or path[0] == '/' or path[-1] == '/': raise AttributeError("Invalid path '%s'" % path) matches = [] for child in self.children: matches += child._get_matching_elements(path.split('/')) return matches def _get_matching_elements(self, tokens): if self.name != tokens[0]: return [] elif len(tokens) == 1: return [self] else: matches = [] for child in self.children: matches += child._get_matching_elements(tokens[1:]) return matches def get_node(self, path): """Similar as get_nodes but checks that exactly one node is found. Node is returned as is (i.e. not in a list) and AttributeError risen if no match or more than one match found. """ nodes = self.get_nodes(path) if len(nodes) == 0: raise AttributeError("No nodes matching path '%s' found" % path) if len(nodes) > 1: raise AttributeError("Multiple nodes matching path '%s' found" % path) return nodes[0] def get_attr(self, name, default=None): """Helper for getting node's attributes. Otherwise equivalent to 'node.attrs.get(name, default)' but raises an AttributeError if no value found and no default given. """ ret = self.attrs.get(name, default) if ret is None: raise AttributeError("No attribute '%s' found" % name) return ret def __getattr__(self, name): """Syntactic sugar for get_nodes (e.g. dom.elem[0].subelem). Differs from get_nodes so that if not matching nodes are found an AttributeError is risen instead of returning an empty list. """ nodes = self.get_nodes(name) if not nodes: raise AttributeError("No nodes matching path '%s' found" % name) return nodes def __getitem__(self, name): """Syntactic sugar for get_node (e.g. dom['elem/subelem'])""" try: return self.get_node(name) except AttributeError: raise IndexError("No node '%s' found" % name) def __repr__(self): """Return node name. Mainly for debugging purposes.""" return self.name
[ [ 1, 0, 0.1429, 0.0095, 0, 0.66, 0, 651, 0, 1, 0, 0, 651, 0, 0 ], [ 3, 0, 0.5857, 0.8381, 0, 0.66, 1, 409, 0, 8, 0, 0, 186, 0, 22 ], [ 2, 1, 0.2476, 0.1238, 1, 0.84...
[ "import etreewrapper", "class DomWrapper(object):\n\n def __init__(self, path=None, string=None, node=None):\n \"\"\"Initialize by giving 'path' to an xml file or xml as a 'string'.\n\n Alternative initialization by giving dom 'node' ment to be used only\n internally. 'path' may actually a...
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from unic import unic def printable_name(string, code_style=False): """Generates and returns printable name from the given string. Examples: 'simple' -> 'Simple' 'name with spaces' -> 'Name With Spaces' 'more spaces' -> 'More Spaces' 'Cases AND spaces' -> 'Cases AND Spaces' '' -> '' If 'code_style' is True: 'mixedCAPSCamel' -> 'Mixed CAPS Camel' 'camelCaseName' -> 'Camel Case Name' 'under_score_name' -> 'Under Score Name' 'under_and space' -> 'Under And Space' 'miXed_CAPS_nAMe' -> 'MiXed CAPS NAMe' '' -> '' """ if code_style: string = string.replace('_', ' ') parts = string.split() if len(parts) == 0: return '' elif len(parts) == 1 and code_style: parts = _splitCamelCaseString(parts[0]) parts = [ part[0].upper() + part[1:] for part in parts if part != '' ] return ' '.join(parts) def _splitCamelCaseString(string): parts = [] current_part = [] string = ' ' + string + ' ' # extra spaces make going through string easier for i in range(1, len(string)-1): # on 1st/last round prev/next is ' ' and char is 1st/last real char prev, char, next = string[i-1:i+2] if _isWordBoundary(prev, char, next): parts.append(''.join(current_part)) current_part = [ char ] else: current_part.append(char) parts.append(''.join(current_part)) # append last part return parts def _isWordBoundary(prev, char, next): if char.isupper(): return (prev.islower() or next.islower()) and prev.isalnum() if char.isdigit(): return prev.isalpha() return prev.isdigit() def plural_or_not(item): count = item if isinstance(item, (int, long)) else len(item) return '' if count == 1 else 's' def seq2str(sequence, quote="'", sep=', ', lastsep=' and '): """Returns sequence in format 'item 1', 'item 2' and 'item 3'""" quote_elem = lambda string: quote + unic(string) + quote if len(sequence) == 0: return '' if len(sequence) == 1: return quote_elem(sequence[0]) elems = [quote_elem(s) for s in sequence[:-2]] elems.append(quote_elem(sequence[-2]) + lastsep + quote_elem(sequence[-1])) return sep.join(elems) def seq2str2(sequence): """Returns sequence in format [ item 1 | item 2 | ... ] """ if not sequence: return '[ ]' return '[ %s ]' % ' | '.join(unic(item) for item in sequence)
[ [ 1, 0, 0.1613, 0.0108, 0, 0.66, 0, 992, 0, 1, 0, 0, 992, 0, 0 ], [ 2, 0, 0.3387, 0.3011, 0, 0.66, 0.1667, 934, 0, 2, 1, 0, 0, 0, 7 ], [ 8, 1, 0.2957, 0.1935, 1, 0....
[ "from unic import unic", "def printable_name(string, code_style=False):\n \"\"\"Generates and returns printable name from the given string.\n\n Examples:\n 'simple' -> 'Simple'\n 'name with spaces' -> 'Name With Spaces'\n 'more spaces' -> 'More Spaces'\n 'Cases AND spaces' -> 'Cas...
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """A module to handle different character widths on the console. Some East Asian characters have width of two on console, and combining characters themselves take no extra space. See issue 604 [1] for more details. It also contains `generate_wild_chars.py` script that was originally used to create the East Asian wild character map. Big thanks for xieyanbo for the script and the original patch. Note that Python's `unicodedata` module is not used here because importing it takes several seconds on Jython. [1] http://code.google.com/p/robotframework/issues/detail?id=604 """ def get_char_width(char): char = ord(char) if _char_in_map(char, _COMBINING_CHARS): return 0 if _char_in_map(char, _EAST_ASIAN_WILD_CHARS): return 2 return 1 def _char_in_map(char, map): for begin, end in map: if char < begin: break if begin <= char <= end: return True return False _COMBINING_CHARS = [(768,879)] _EAST_ASIAN_WILD_CHARS = [ (888, 889), (896, 899), (909, 909), (1316, 1328), (1368, 1368), (1416, 1416), (1420, 1424), (1481, 1487), (1516, 1519), (1526, 1535), (1541, 1541), (1565, 1565), (1631, 1631), (1867, 1868), (1971, 1983), (2044, 2304), (2363, 2363), (2383, 2383), (2390, 2391), (2420, 2426), (2436, 2436), (2446, 2446), (2450, 2450), (2481, 2481), (2484, 2485), (2491, 2491), (2502, 2502), (2506, 2506), (2512, 2518), (2521, 2523), (2532, 2533), (2556, 2560), (2571, 2574), (2578, 2578), (2609, 2609), (2615, 2615), (2619, 2619), (2627, 2630), (2634, 2634), (2639, 2640), (2643, 2648), (2655, 2661), (2679, 2688), (2702, 2702), (2729, 2729), (2740, 2740), (2747, 2747), (2762, 2762), (2767, 2767), (2770, 2783), (2789, 2789), (2802, 2816), (2829, 2830), (2834, 2834), (2865, 2865), (2874, 2875), (2886, 2886), (2890, 2890), (2895, 2901), (2905, 2907), (2916, 2917), (2931, 2945), (2955, 2957), (2966, 2968), (2973, 2973), (2977, 2978), (2982, 2983), (2988, 2989), (3003, 3005), (3012, 3013), (3022, 3023), (3026, 3030), (3033, 3045), (3068, 3072), (3085, 3085), (3113, 3113), (3130, 3132), (3145, 3145), (3151, 3156), (3162, 3167), (3173, 3173), (3185, 3191), (3201, 3201), (3213, 3213), (3241, 3241), (3258, 3259), (3273, 3273), (3279, 3284), (3288, 3293), (3300, 3301), (3315, 3329), (3341, 3341), (3369, 3369), (3387, 3388), (3401, 3401), (3407, 3414), (3417, 3423), (3429, 3429), (3447, 3448), (3457, 3457), (3479, 3481), (3516, 3516), (3519, 3519), (3528, 3529), (3532, 3534), (3543, 3543), (3553, 3569), (3574, 3584), (3644, 3646), (3677, 3712), (3717, 3718), (3723, 3724), (3727, 3731), (3744, 3744), (3750, 3750), (3753, 3753), (3770, 3770), (3775, 3775), (3783, 3783), (3791, 3791), (3803, 3803), (3807, 3839), (3949, 3952), (3981, 3983), (4029, 4029), (4053, 4095), (4251, 4253), (4295, 4303), (4350, 4447), (4516, 4519), (4603, 4607), (4686, 4687), (4697, 4697), (4703, 4703), (4750, 4751), (4790, 4791), (4801, 4801), (4807, 4807), (4881, 4881), (4887, 4887), (4956, 4958), (4990, 4991), (5019, 5023), (5110, 5120), (5752, 5759), (5790, 5791), (5874, 5887), (5909, 5919), (5944, 5951), (5973, 5983), (6001, 6001), (6005, 6015), (6111, 6111), (6123, 6127), (6139, 6143), (6170, 6175), (6265, 6271), (6316, 6399), (6430, 6431), (6445, 6447), (6461, 6463), (6466, 6467), (6511, 6511), (6518, 6527), (6571, 6575), (6603, 6607), (6619, 6621), (6685, 6685), (6689, 6911), (6989, 6991), (7038, 7039), (7084, 7085), (7099, 7167), (7225, 7226), (7243, 7244), (7297, 7423), (7656, 7677), (7959, 7959), (7967, 7967), (8007, 8007), (8015, 8015), (8026, 8026), (8030, 8030), (8063, 8063), (8133, 8133), (8149, 8149), (8176, 8177), (8191, 8191), (8294, 8297), (8307, 8307), (8341, 8351), (8375, 8399), (8434, 8447), (8529, 8530), (8586, 8591), (9002, 9002), (9193, 9215), (9256, 9279), (9292, 9311), (9887, 9887), (9918, 9919), (9925, 9984), (9994, 9995), (10060, 10060), (10067, 10069), (10079, 10080), (10134, 10135), (10175, 10175), (10189, 10191), (11086, 11087), (11094, 11263), (11359, 11359), (11390, 11391), (11500, 11512), (11559, 11567), (11623, 11630), (11633, 11647), (11672, 11679), (11695, 11695), (11711, 11711), (11727, 11727), (11743, 11743), (11826, 12350), (12353, 19903), (19969, 42239), (42541, 42559), (42593, 42593), (42613, 42619), (42649, 42751), (42894, 43002), (43053, 43071), (43129, 43135), (43206, 43213), (43227, 43263), (43349, 43358), (43361, 43519), (43576, 43583), (43599, 43599), (43611, 43611), (43617, 55295), (63745, 64255), (64264, 64274), (64281, 64284), (64317, 64317), (64322, 64322), (64434, 64466), (64833, 64847), (64913, 64913), (64969, 65007), (65023, 65023), (65041, 65055), (65064, 65135), (65277, 65278), (65281, 65376), (65472, 65473), (65481, 65481), (65489, 65489), (65497, 65497), (65502, 65511), (65520, 65528), (65535, 65535), ]
[ [ 8, 0, 0.194, 0.1207, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 2, 0, 0.2931, 0.0603, 0, 0.66, 0.25, 601, 0, 1, 1, 0, 0, 0, 3 ], [ 14, 1, 0.2759, 0.0086, 1, 0.4, ...
[ "\"\"\"A module to handle different character widths on the console.\n\nSome East Asian characters have width of two on console, and combining\ncharacters themselves take no extra space.\n\nSee issue 604 [1] for more details. It also contains `generate_wild_chars.py`\nscript that was originally used to create the E...
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import sys # Need different unic implementations for different Pythons because: # 1) Importing unicodedata module on Jython takes a very long time, and doesn't # seem to be necessary as Java probably already handles normalization. # Furthermore, Jython on Java 1.5 doesn't even have unicodedata.normalize. # 2) IronPython 2.6 doesn't have unicodedata and probably doesn't need it. # 3) CPython doesn't automatically normalize Unicode strings. if sys.platform.startswith('java'): from java.lang import Object, Class def unic(item, *args): # http://bugs.jython.org/issue1564 if isinstance(item, Object) and not isinstance(item, Class): item = item.toString() # http://bugs.jython.org/issue1563 return _unic(item, *args) elif sys.platform == 'cli': def unic(item, *args): return _unic(item, *args) else: from unicodedata import normalize def unic(item, *args): return normalize('NFC', _unic(item, *args)) def _unic(item, *args): # Based on a recipe from http://code.activestate.com/recipes/466341 try: return unicode(item, *args) except UnicodeError: try: ascii_text = str(item).encode('string_escape') except UnicodeError: return u"<unrepresentable object '%s'>" % item.__class__.__name__ else: return unicode(ascii_text) def safe_repr(item): try: return unic(repr(item)) except UnicodeError: return repr(unic(item))
[ [ 1, 0, 0.25, 0.0167, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 4, 0, 0.5417, 0.2667, 0, 0.66, 0.3333, 0, 3, 0, 0, 0, 0, 0, 8 ], [ 1, 1, 0.4333, 0.0167, 1, 0.62, ...
[ "import sys", "if sys.platform.startswith('java'):\n from java.lang import Object, Class\n def unic(item, *args):\n # http://bugs.jython.org/issue1564\n if isinstance(item, Object) and not isinstance(item, Class):\n item = item.toString() # http://bugs.jython.org/issue1563\n ...
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import re from UserDict import UserDict _WHITESPACE_REGEXP = re.compile('\s+') def normalize(string, ignore=[], caseless=True, spaceless=True): """Normalizes given string according to given spec. By default string is turned to lower case and all whitespace is removed. Additional characters can be removed by giving them in `ignore` list. """ if spaceless: string = _WHITESPACE_REGEXP.sub('', string) if caseless: string = string.lower() ignore = [i.lower() for i in ignore] for ign in ignore: string = string.replace(ign, '') return string def normalize_tags(tags): """Returns tags sorted and duplicates, empty, and NONE removed. If duplicate tags have different case/space, the one used first wins. """ norm = NormalizedDict(((t, 1) for t in tags), ignore=['_']) for removed in '', 'NONE': if removed in norm: norm.pop(removed) return norm.keys() class NormalizedDict(UserDict): """Custom dictionary implementation automatically normalizing keys.""" def __init__(self, initial=None, ignore=[], caseless=True, spaceless=True): """Initializes with possible initial value and normalizing spec. Initial values can be either a dictionary or an iterable of name/value pairs. In the latter case items are added in the given order. Normalizing spec has exact same semantics as with `normalize` method. """ UserDict.__init__(self) self._keys = {} self._normalize = lambda s: normalize(s, ignore, caseless, spaceless) if initial: self._add_initial(initial) def _add_initial(self, items): if hasattr(items, 'items'): items = items.items() for key, value in items: self[key] = value def update(self, dict=None, **kwargs): if dict: UserDict.update(self, dict) for key in dict: self._add_key(key) if kwargs: self.update(kwargs) def _add_key(self, key): nkey = self._normalize(key) self._keys.setdefault(nkey, key) return nkey def set(self, key, value): nkey = self._add_key(key) self.data[nkey] = value __setitem__ = set def get(self, key, default=None): try: return self.__getitem__(key) except KeyError: return default def __getitem__(self, key): return self.data[self._normalize(key)] def pop(self, key): nkey = self._normalize(key) del self._keys[nkey] return self.data.pop(nkey) __delitem__ = pop def has_key(self, key): return self.data.has_key(self._normalize(key)) __contains__ = has_key def keys(self): return [self._keys[nkey] for nkey in sorted(self._keys)] def __iter__(self): return iter(self.keys()) def values(self): return [self[key] for key in self] def items(self): return [(key, self[key]) for key in self] def copy(self): copy = UserDict.copy(self) copy._keys = self._keys.copy() return copy def __str__(self): return str(dict(self.items()))
[ [ 1, 0, 0.1145, 0.0076, 0, 0.66, 0, 540, 0, 1, 0, 0, 540, 0, 0 ], [ 1, 0, 0.1221, 0.0076, 0, 0.66, 0.2, 351, 0, 1, 0, 0, 351, 0, 0 ], [ 14, 0, 0.145, 0.0076, 0, 0.6...
[ "import re", "from UserDict import UserDict", "_WHITESPACE_REGEXP = re.compile('\\s+')", "def normalize(string, ignore=[], caseless=True, spaceless=True):\n \"\"\"Normalizes given string according to given spec.\n\n By default string is turned to lower case and all whitespace is removed.\n Additional...
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from argumentparser import ArgumentParser from connectioncache import ConnectionCache from domwrapper import DomWrapper from encoding import decode_output, encode_output, decode_from_file_system from error import (get_error_message, get_error_details, ErrorDetails, RERAISED_EXCEPTIONS) from escaping import escape, unescape from htmlutils import html_format, html_escape, html_attr_escape from htmlwriter import HtmlWriter from importing import simple_import, import_ from match import eq, eq_any, matches, matches_any from misc import plural_or_not, printable_name, seq2str, seq2str2 from normalizing import normalize, normalize_tags, NormalizedDict from robotpath import normpath, abspath, get_link_path from robottime import (get_timestamp, get_start_timestamp, format_time, get_time, get_elapsed_time, elapsed_time_to_string, timestr_to_secs, secs_to_timestr, secs_to_timestamp, timestamp_to_secs, parse_time) from text import (cut_long_message, format_assign_message, pad_console_length, get_console_length) from unic import unic, safe_repr from xmlwriter import XmlWriter import sys is_jython = sys.platform.startswith('java') del sys
[ [ 1, 0, 0.375, 0.025, 0, 0.66, 0, 215, 0, 1, 0, 0, 215, 0, 0 ], [ 1, 0, 0.4, 0.025, 0, 0.66, 0.0556, 964, 0, 1, 0, 0, 964, 0, 0 ], [ 1, 0, 0.425, 0.025, 0, 0.66, ...
[ "from argumentparser import ArgumentParser", "from connectioncache import ConnectionCache", "from domwrapper import DomWrapper", "from encoding import decode_output, encode_output, decode_from_file_system", "from error import (get_error_message, get_error_details, ErrorDetails,\n RERAISED_...
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from normalizing import NormalizedDict class ConnectionCache: """Connection cache for different Robot test libraries that use connections. This cache stores connections and allows switching between them using generated indexes or user given aliases. Can be used for example by web testing libraries where there's need for multiple concurrent connections. Note that in most cases there should be only one instance of this class but this is not enforced. """ def __init__(self, no_current_msg='No open connection'): self.current = self._no_current = _NoConnection(no_current_msg) self.current_index = None self._connections = [] self._aliases = NormalizedDict() self._no_current_msg = no_current_msg def register(self, connection, alias=None): """Registers given connection with optional alias and returns its index. Given connection is set to be the current connection. Alias must be a string. The index of the first connection after initialization or close_all or empty_cache is 1, second is 2, etc. """ self.current = connection self._connections.append(connection) self.current_index = len(self._connections) if isinstance(alias, basestring): self._aliases[alias] = self.current_index return self.current_index def switch(self, index_or_alias): """Switches to the connection specified by given index or alias. If alias is given it must be a string. Indexes can be either integers or strings that can be converted into integer. Raises RuntimeError if no connection with given index or alias found. """ try: index = self._get_index(index_or_alias) except ValueError: raise RuntimeError("Non-existing index or alias '%s'" % index_or_alias) self.current = self._connections[index-1] self.current_index = index return self.current def close_all(self, closer_method='close'): """Closes connections using given closer method and empties cache. If simply calling the closer method is not adequate for closing connections, clients should close connections themselves and use empty_cache afterwards. """ for conn in self._connections: getattr(conn, closer_method)() self.empty_cache() return self.current def empty_cache(self): """Empties the connections cache. Indexes of new connections starts from 1 after this.""" self.current = self._no_current self.current_index = None self._connections = [] self._aliases = NormalizedDict() def _get_index(self, index_or_alias): try: return self._resolve_alias(index_or_alias) except ValueError: return self._resolve_index(index_or_alias) def _resolve_alias(self, alias): if isinstance(alias, basestring): try: return self._aliases[alias] except KeyError: pass raise ValueError def _resolve_index(self, index): index = int(index) if not 0 < index <= len(self._connections): raise ValueError return index class _NoConnection: def __init__(self, msg): self._msg = msg def __getattr__(self, name): if name.startswith('__') and name.endswith('__'): raise AttributeError raise RuntimeError(self._msg) def __nonzero__(self): return False
[ [ 1, 0, 0.1261, 0.0084, 0, 0.66, 0, 901, 0, 1, 0, 0, 901, 0, 0 ], [ 3, 0, 0.5168, 0.7395, 0, 0.66, 0.5, 797, 0, 8, 0, 0, 0, 0, 16 ], [ 8, 1, 0.2017, 0.0756, 1, 0.97...
[ "from normalizing import NormalizedDict", "class ConnectionCache:\n\n \"\"\"Connection cache for different Robot test libraries that use connections.\n\n This cache stores connections and allows switching between them using\n generated indexes or user given aliases. Can be used for example by web\n te...
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import re from normalizing import normalize _match_pattern_tokenizer = re.compile('(\*|\?)') def eq(str1, str2, ignore=[], caseless=True, spaceless=True): str1 = normalize(str1, ignore, caseless, spaceless) str2 = normalize(str2, ignore, caseless, spaceless) return str1 == str2 def eq_any(str_, str_list, ignore=[], caseless=True, spaceless=True): str_ = normalize(str_, ignore, caseless, spaceless) for s in str_list: if str_ == normalize(s, ignore, caseless, spaceless): return True return False def matches(string, pattern, ignore=[], caseless=True, spaceless=True): string = normalize(string, ignore, caseless, spaceless) pattern = normalize(pattern, ignore, caseless, spaceless) regexp = _get_match_regexp(pattern) return re.match(regexp, string, re.DOTALL) is not None def _get_match_regexp(pattern): regexp = [] for token in _match_pattern_tokenizer.split(pattern): if token == '*': regexp.append('.*') elif token == '?': regexp.append('.') else: regexp.append(re.escape(token)) return '^%s$' % ''.join(regexp) def matches_any(string, patterns, ignore=[], caseless=True, spaceless=True): for pattern in patterns: if matches(string, pattern, ignore, caseless, spaceless): return True return False
[ [ 1, 0, 0.2667, 0.0167, 0, 0.66, 0, 540, 0, 1, 0, 0, 540, 0, 0 ], [ 1, 0, 0.3, 0.0167, 0, 0.66, 0.1429, 901, 0, 1, 0, 0, 901, 0, 0 ], [ 14, 0, 0.35, 0.0167, 0, 0.66...
[ "import re", "from normalizing import normalize", "_match_pattern_tokenizer = re.compile('(\\*|\\?)')", "def eq(str1, str2, ignore=[], caseless=True, spaceless=True):\n str1 = normalize(str1, ignore, caseless, spaceless)\n str2 = normalize(str2, ignore, caseless, spaceless)\n return str1 == str2", ...
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import sys from xml.sax.saxutils import XMLGenerator from xml.sax.xmlreader import AttributesImpl from abstractxmlwriter import AbstractXmlWriter class XmlWriter(AbstractXmlWriter): def __init__(self, path): self.path = path self._output = open(path, 'wb') self._writer = XMLGenerator(self._output, encoding='UTF-8') self._writer.startDocument() self.closed = False def _start(self, name, attrs): self._writer.startElement(name, AttributesImpl(attrs)) def _content(self, content): self._writer.characters(content) def _end(self, name): self._writer.endElement(name) # Workaround for http://ironpython.codeplex.com/workitem/29474 if sys.platform == 'cli': def _escape(self, content): return AbstractXmlWriter._escape(self, content).encode('UTF-8')
[ [ 1, 0, 0.3488, 0.0233, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.3721, 0.0233, 0, 0.66, 0.25, 759, 0, 1, 0, 0, 759, 0, 0 ], [ 1, 0, 0.3953, 0.0233, 0, 0....
[ "import sys", "from xml.sax.saxutils import XMLGenerator", "from xml.sax.xmlreader import AttributesImpl", "from abstractxmlwriter import AbstractXmlWriter", "class XmlWriter(AbstractXmlWriter):\n\n def __init__(self, path):\n self.path = path\n self._output = open(path, 'wb')\n self...
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. RESERVED_KEYWORDS = [ 'for', 'while', 'break', 'continue', 'end', 'if', 'else', 'elif', 'else if', 'return' ] class Reserved: ROBOT_LIBRARY_SCOPE = 'GLOBAL' def get_keyword_names(self): return RESERVED_KEYWORDS def run_keyword(self, name, args): raise Exception("'%s' is a reserved keyword" % name.title())
[ [ 14, 0, 0.569, 0.069, 0, 0.66, 0, 112, 0, 0, 0, 0, 0, 5, 0 ], [ 3, 0, 0.8276, 0.3103, 0, 0.66, 1, 466, 0, 2, 0, 0, 0, 0, 2 ], [ 14, 1, 0.7586, 0.0345, 1, 0, 0,...
[ "RESERVED_KEYWORDS = [ 'for', 'while', 'break', 'continue', 'end',\n 'if', 'else', 'elif', 'else if', 'return' ]", "class Reserved:\n\n ROBOT_LIBRARY_SCOPE = 'GLOBAL'\n\n def get_keyword_names(self):\n return RESERVED_KEYWORDS\n\n def run_keyword(self, name, args):", " RO...
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. def none_shall_pass(who): if who is not None: raise AssertionError('None shall pass!') print '*HTML* <object width="480" height="385"><param name="movie" value="http://www.youtube.com/v/dhRUe-gz690&hl=en_US&fs=1&rel=0&color1=0x234900&color2=0x4e9e00"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/dhRUe-gz690&hl=en_US&fs=1&rel=0&color1=0x234900&color2=0x4e9e00" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="480" height="385"></embed></object>'
[ [ 2, 0, 0.9211, 0.2105, 0, 0.66, 0, 93, 0, 1, 0, 0, 0, 0, 2 ], [ 4, 1, 0.9211, 0.1053, 1, 0.47, 0, 0, 0, 0, 0, 0, 0, 0, 1 ], [ 8, 1, 1, 0.0526, 1, 0.47, 1, ...
[ "def none_shall_pass(who):\n if who is not None:\n raise AssertionError('None shall pass!')\n print('*HTML* <object width=\"480\" height=\"385\"><param name=\"movie\" value=\"http://www.youtube.com/v/dhRUe-gz690&hl=en_US&fs=1&rel=0&color1=0x234900&color2=0x4e9e00\"></param><param name=\"allowFullScreen...
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """A test library providing dialogs for interacting with users. `Dialogs` is Robot Framework's standard library that provides means for pausing the test execution and getting input from users. The dialogs are slightly different depending on are tests run on Python or Jython but they provide the same functionality. Note: Dialogs library cannot be used with timeouts on Windows with Python. """ __all__ = ['execute_manual_step', 'get_value_from_user', 'get_selection_from_user', 'pause_execution'] import sys try: from robot.version import get_version as _get_version except ImportError: __version__ = 'unknown' else: __version__ = _get_version() DIALOG_TITLE = 'Robot Framework' def pause_execution(message='Test execution paused. Press OK to continue.'): """Pauses the test execution and shows dialog with the text `message`. """ MessageDialog(message) def execute_manual_step(message, default_error=''): """Pauses the test execution until user sets the keyword status. `message` is the instruction shown in the dialog. User can select PASS or FAIL, and in the latter case an additional dialog is opened for defining the error message. `default_error` is the possible default value shown in the error message dialog. """ if not PassFailDialog(message).result: msg = get_value_from_user('Give error message:', default_error) raise AssertionError(msg) def get_value_from_user(message, default_value=''): """Pauses the test execution and asks user to input a value. `message` is the instruction shown in the dialog. `default_value` is the possible default value shown in the input field. Selecting 'Cancel' fails the keyword. """ return _validate_user_input(InputDialog(message, default_value).result) def get_selection_from_user(message, *values): """Pauses the test execution and asks user to select value `message` is the instruction shown in the dialog. and `values` are the options given to the user. Selecting 'Cancel' fails the keyword. This keyword was added into Robot Framework 2.1.2. """ return _validate_user_input(SelectionDialog(message, values).result) def _validate_user_input(value): if value is None: raise ValueError('No value provided by user') return value if not sys.platform.startswith('java'): from Tkinter import (Tk, Toplevel, Frame, Listbox, Label, Button, BOTH, END, LEFT) import tkMessageBox import tkSimpleDialog from threading import currentThread def prevent_execution_with_timeouts(method): def check_timeout(*args): if 'linux' not in sys.platform \ and currentThread().getName() != 'MainThread': raise RuntimeError('Dialogs library is not supported with ' 'timeouts on Python on this platform.') return method(*args) return check_timeout class _AbstractTkDialog(Toplevel): @prevent_execution_with_timeouts def __init__(self, title): parent = Tk() parent.withdraw() Toplevel.__init__(self, parent) self._init_dialog(parent, title) self._create_body() self._create_buttons() self.result = None self._initial_focus.focus_set() self.wait_window(self) def _init_dialog(self, parent, title): self.title(title) self.grab_set() self.protocol("WM_DELETE_WINDOW", self._right_clicked) self.geometry("+%d+%d" % (parent.winfo_rootx()+150, parent.winfo_rooty()+150)) def _create_body(self): frame = Frame(self) self._initial_focus = self.create_components(frame) frame.pack(padx=5, pady=5, expand=1, fill=BOTH) def _create_buttons(self): frame = Frame(self) self._create_button(frame, self._left_button, self._left_clicked) self._create_button(frame, self._right_button, self._right_clicked) self.bind("<Escape>", self._right_clicked) frame.pack() def _create_button(self, parent, label, command): w = Button(parent, text=label, width=10, command=command) w.pack(side=LEFT, padx=5, pady=5) def _left_clicked(self, event=None): if not self.validate(): self._initial_focus.focus_set() return self.withdraw() self.apply() self.destroy() def _right_clicked(self, event=None): self.destroy() def create_components(self, parent): raise NotImplementedError() def validate(self): raise NotImplementedError() def apply(self): raise NotImplementedError() class MessageDialog(object): @prevent_execution_with_timeouts def __init__(self, message): Tk().withdraw() tkMessageBox.showinfo(DIALOG_TITLE, message) class InputDialog(object): @prevent_execution_with_timeouts def __init__(self, message, default): Tk().withdraw() self.result = tkSimpleDialog.askstring(DIALOG_TITLE, message, initialvalue=default) class SelectionDialog(_AbstractTkDialog): _left_button = 'OK' _right_button = 'Cancel' def __init__(self, message, values): self._message = message self._values = values _AbstractTkDialog.__init__(self, "Select one option") def create_components(self, parent): Label(parent, text=self._message).pack(fill=BOTH) self._listbox = Listbox(parent) self._listbox.pack(fill=BOTH) for item in self._values: self._listbox.insert(END, item) return self._listbox def validate(self): return bool(self._listbox.curselection()) def apply(self): self.result = self._listbox.get(self._listbox.curselection()) class PassFailDialog(_AbstractTkDialog): _left_button = 'PASS' _right_button = 'FAIL' def __init__(self, message): self._message = message _AbstractTkDialog.__init__(self, DIALOG_TITLE) def create_components(self, parent): label = Label(parent, text=self._message) label.pack(fill=BOTH) return label def validate(self): return True def apply(self): self.result = True else: import time from javax.swing import JOptionPane from javax.swing.JOptionPane import PLAIN_MESSAGE, UNINITIALIZED_VALUE, \ YES_NO_OPTION, OK_CANCEL_OPTION, DEFAULT_OPTION class _AbstractSwingDialog: def __init__(self, message): self.result = self._show_dialog(message) def _show_dialog(self, message): self._init_dialog(message) self._show_dialog_and_wait_it_to_be_closed() return self._get_value() def _show_dialog_and_wait_it_to_be_closed(self): dialog = self._pane.createDialog(None, DIALOG_TITLE) dialog.setModal(0); dialog.show() while dialog.isShowing(): time.sleep(0.2) dialog.dispose() def _get_value(self): value = self._pane.getInputValue() if value == UNINITIALIZED_VALUE: return None return value class MessageDialog(_AbstractSwingDialog): def _init_dialog(self, message): self._pane = JOptionPane(message, PLAIN_MESSAGE, DEFAULT_OPTION) class InputDialog(_AbstractSwingDialog): def __init__(self, message, default): self._default = default _AbstractSwingDialog.__init__(self, message) def _init_dialog(self, message): self._pane = JOptionPane(message, PLAIN_MESSAGE, OK_CANCEL_OPTION) self._pane.setWantsInput(True) self._pane.setInitialSelectionValue(self._default) class SelectionDialog(_AbstractSwingDialog): def __init__(self, message, options): self._options = options _AbstractSwingDialog.__init__(self, message) def _init_dialog(self, message): self._pane = JOptionPane(message, PLAIN_MESSAGE, OK_CANCEL_OPTION) self._pane.setWantsInput(True) self._pane.setSelectionValues(self._options) class PassFailDialog(_AbstractSwingDialog): def _init_dialog(self, message): self._buttons = ['PASS', 'FAIL'] self._pane = JOptionPane(message, PLAIN_MESSAGE, YES_NO_OPTION, None, self._buttons, 'PASS') def _get_value(self): value = self._pane.getValue() if value in self._buttons and self._buttons.index(value) == 0: return True return False
[ [ 8, 0, 0.0678, 0.0305, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 14, 0, 0.0898, 0.0068, 0, 0.66, 0.1, 272, 0, 0, 0, 0, 0, 5, 0 ], [ 1, 0, 0.0983, 0.0034, 0, 0.66, ...
[ "\"\"\"A test library providing dialogs for interacting with users.\n\n`Dialogs` is Robot Framework's standard library that provides means\nfor pausing the test execution and getting input from users. The\ndialogs are slightly different depending on are tests run on Python or\nJython but they provide the same funct...
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import telnetlib import time import re import inspect from robot.version import get_version from robot import utils class Telnet: """A test library providing communication over Telnet connections. `Telnet` is Robot Framework's standard library that makes it possible to connect to Telnet servers and execute commands on the opened connections. See `Open Connection` and `Switch Connection` for details on how to handle multiple simultaneous connections. The responses are expected to be ASCII encoded and all non-ASCII characters are silently ignored. """ ROBOT_LIBRARY_SCOPE = 'TEST_SUITE' ROBOT_LIBRARY_VERSION = get_version() def __init__(self, timeout=3.0, newline='CRLF', prompt=None, prompt_is_regexp=False): """Telnet library can be imported with optional arguments. Initialization parameters are used as default values when new connections are opened with `Open Connection` keyword. They can also be set after opening the connection using the `Set Timeout`, `Set Newline` and `Set Prompt` keywords. See these keywords for more information. Examples (use only one of these): | *Setting* | *Value* | *Value* | *Value* | *Value* | *Value* | *Comment* | | Library | Telnet | | | | | # default values | | Library | Telnet | 0.5 | | | | # set only timeout | | Library | Telnet | | LF | | | # set only newline | | Library | Telnet | 2.0 | LF | | | # set timeout and newline | | Library | Telnet | 2.0 | CRLF | $ | | # set also prompt | | Library | Telnet | 2.0 | LF | ($|~) | True | # set prompt with simple regexp | """ self._timeout = timeout == '' and 3.0 or timeout self._newline = newline == '' and 'CRLF' or newline self._prompt = (prompt, prompt_is_regexp) self._cache = utils.ConnectionCache() self._conn = None self._conn_kws = self._lib_kws = None def get_keyword_names(self): return self._get_library_keywords() + self._get_connection_keywords() def _get_library_keywords(self): if self._lib_kws is None: self._lib_kws = [ name for name in dir(self) if not name.startswith('_') and name != 'get_keyword_names' and inspect.ismethod(getattr(self, name)) ] return self._lib_kws def _get_connection_keywords(self): if self._conn_kws is None: conn = self._get_connection() excluded = [ name for name in dir(telnetlib.Telnet()) if name not in ['write', 'read', 'read_until'] ] self._conn_kws = [ name for name in dir(conn) if not name.startswith('_') and name not in excluded and inspect.ismethod(getattr(conn, name)) ] return self._conn_kws def __getattr__(self, name): if name not in self._get_connection_keywords(): raise AttributeError(name) # If no connection is initialized, get attributes from a non-active # connection. This makes it possible for Robot to create keyword # handlers when it imports the library. conn = self._conn is None and self._get_connection() or self._conn return getattr(conn, name) def open_connection(self, host, alias=None, port=23, timeout=None, newline=None, prompt=None, prompt_is_regexp=False): """Opens a new Telnet connection to the given host and port. Possible already opened connections are cached. Returns the index of this connection, which can be used later to switch back to the connection. The index starts from 1 and is reset back to it when the `Close All Connections` keyword is used. The optional `alias` is a name for the connection, and it can be used for switching between connections, similarly as the index. See `Switch Connection` for more details about that. The `timeout`, `newline`, `prompt` and `prompt_is_regexp` arguments get default values when the library is taken into use, but setting them here overrides those values for this connection. See `importing` for more information. """ if timeout is None or timeout == '': timeout = self._timeout if newline is None: newline = self._newline if prompt is None: prompt, prompt_is_regexp = self._prompt print '*INFO* Opening connection to %s:%s with prompt: %s' \ % (host, port, self._prompt) self._conn = self._get_connection(host, port, timeout, newline, prompt, prompt_is_regexp) return self._cache.register(self._conn, alias) def _get_connection(self, *args): """Can be overridden to use a custom connection.""" return TelnetConnection(*args) def switch_connection(self, index_or_alias): """Switches between active connections using an index or alias. The index is got from `Open Connection` keyword, and an alias can be given to it. Returns the index of previously active connection. Example: | Open Connection | myhost.net | | | | Login | john | secret | | | Write | some command | | | | Open Connection | yourhost.com | 2nd conn | | | Login | root | password | | | Write | another cmd | | | | ${old index}= | Switch Connection | 1 | # index | | Write | something | | | | Switch Connection | 2nd conn | # alias | | | Write | whatever | | | | Switch Connection | ${old index} | # back to original again | | [Teardown] | Close All Connections | | The example above expects that there were no other open connections when opening the first one, because it used index '1' when switching to the connection later. If you are not sure about that, you can store the index into a variable as shown below. | ${id} = | Open Connection | myhost.net | | # Do something ... | | | | Switch Connection | ${id} | | """ old_index = self._cache.current_index self._conn = self._cache.switch(index_or_alias) return old_index def close_all_connections(self): """Closes all open connections and empties the connection cache. After this keyword, new indexes got from the `Open Connection` keyword are reset to 1. This keyword should be used in a test or suite teardown to make sure all connections are closed. """ self._conn = self._cache.close_all() class TelnetConnection(telnetlib.Telnet): def __init__(self, host=None, port=23, timeout=3.0, newline='CRLF', prompt=None, prompt_is_regexp=False): port = port == '' and 23 or int(port) telnetlib.Telnet.__init__(self, host, port) self.set_timeout(timeout) self.set_newline(newline) self.set_prompt(prompt, prompt_is_regexp) self._default_log_level = 'INFO' self.set_option_negotiation_callback(self._negotiate_echo_on) def set_timeout(self, timeout): """Sets the timeout used in read operations to the given value. `timeout` is given in Robot Framework's time format (e.g. 1 minute 20 seconds) that is explained in the User Guide. Read operations that expect some output to appear (`Read Until`, `Read Until Regexp`, `Read Until Prompt`) use this timeout and fail if the expected output has not appeared when this timeout expires. The old timeout is returned and can be used to restore it later. Example: | ${tout} = | Set Timeout | 2 minute 30 seconds | | Do Something | | Set Timeout | ${tout} | """ old = getattr(self, '_timeout', 3.0) self._timeout = utils.timestr_to_secs(timeout) return utils.secs_to_timestr(old) def set_newline(self, newline): """Sets the newline used by the `Write` keyword. Newline can be given either in escaped format using '\\n' and '\\r', or with special 'LF' and 'CR' syntax. Examples: | Set Newline | \\n | | Set Newline | CRLF | Correct newline to use depends on the system and the default value is 'CRLF'. The old newline is returned and can be used to restore it later. See `Set Prompt` or `Set Timeout` for an example. """ old = getattr(self, '_newline', 'CRLF') self._newline = newline.upper().replace('LF','\n').replace('CR','\r') return old def close_connection(self, loglevel=None): """Closes the current Telnet connection and returns any remaining output. See `Read` for more information on `loglevel`. """ telnetlib.Telnet.close(self) ret = self.read_all().decode('ASCII', 'ignore') self._log(ret, loglevel) return ret def login(self, username, password, login_prompt='login: ', password_prompt='Password: '): """Logs in to the Telnet server with the given user information. The login keyword reads from the connection until login_prompt is encountered and then types the user name. Then it reads until password_prompt is encountered and types the password. The rest of the output (if any) is also read, and all the text that has been read is returned as a single string. If a prompt has been set to this connection, either with `Open Connection` or `Set Prompt`, this keyword reads the output until the prompt is found. Otherwise, the keyword sleeps for a second and reads everything that is available. """ ret = self.read_until(login_prompt, 'TRACE').decode('ASCII', 'ignore') self.write_bare(username + self._newline) ret += username + '\n' ret += self.read_until(password_prompt, 'TRACE').decode('ASCII', 'ignore') self.write_bare(password + self._newline) ret += '*' * len(password) + '\n' if self._prompt_is_set(): try: ret += self.read_until_prompt('TRACE') except AssertionError: self._verify_login(ret) raise else: ret += self._verify_login(ret) self._log(ret) return ret def _verify_login(self, ret): # It is necessary to wait for the 'login incorrect' message to appear. time.sleep(1) while True: try: ret += self.read_until('\n', 'TRACE').decode('ASCII', 'ignore') except AssertionError: return ret else: if 'Login incorrect' in ret: self._log(ret) raise AssertionError("Login incorrect") def write(self, text, loglevel=None): """Writes the given text over the connection and appends a newline. Consumes the written text (until the appended newline) from the output and returns it. The given text must not contain newlines. Note: This keyword does not return the possible output of the executed command. To get the output, one of the `Read XXX` keywords must be used. See `Read` for more information on `loglevel`. """ if self._newline in text: raise RuntimeError("Write cannot be used with string containing " "newlines. Use 'Write Bare' instead.") text += self._newline self.write_bare(text) # Can't read until 'text' because long lines are cut strangely in the output return self.read_until(self._newline, loglevel) def write_bare(self, text): """Writes the given text over the connection without appending a newline. Does not consume the written text. """ try: text = str(text) except UnicodeError: raise ValueError('Only ASCII characters are allowed in Telnet. ' 'Got: %s' % text) telnetlib.Telnet.write(self, text) def write_until_expected_output(self, text, expected, timeout, retry_interval, loglevel=None): """Writes the given text repeatedly, until `expected` appears in the output. `text` is written without appending a newline. `retry_interval` defines the time waited before writing `text` again. `text` is consumed from the output before `expected` is tried to be read. If `expected` does not appear in the output within `timeout`, this keyword fails. See `Read` for more information on `loglevel`. Example: | Write Until Expected Output | ps -ef| grep myprocess\\n | myprocess | | ... | 5s | 0.5s | This writes the 'ps -ef | grep myprocess\\n', until 'myprocess' appears on the output. The command is written every 0.5 seconds and the keyword ,fails if 'myprocess' does not appear in the output in 5 seconds. """ timeout = utils.timestr_to_secs(timeout) retry_interval = utils.timestr_to_secs(retry_interval) starttime = time.time() while time.time() - starttime < timeout: self.write_bare(text) self.read_until(text, loglevel) ret = telnetlib.Telnet.read_until(self, expected, retry_interval).decode('ASCII', 'ignore') self._log(ret, loglevel) if ret.endswith(expected): return ret raise AssertionError("No match found for '%s' in %s" % (expected, utils.secs_to_timestr(timeout))) def read(self, loglevel=None): """Reads and returns/logs everything that is currently available in the output. The read message is always returned and logged. The default log level is either 'INFO', or the level set with `Set Default Log Level`. `loglevel` can be used to override the default log level, and the available levels are TRACE, DEBUG, INFO, and WARN. """ ret = self.read_very_eager().decode('ASCII', 'ignore') self._log(ret, loglevel) return ret def read_until(self, expected, loglevel=None): """Reads from the current output, until expected is encountered. Text up to and including the match is returned. If no match is found, the keyword fails. See `Read` for more information on `loglevel`. """ ret = telnetlib.Telnet.read_until(self, expected, self._timeout).decode('ASCII', 'ignore') self._log(ret, loglevel) if not ret.endswith(expected): raise AssertionError("No match found for '%s' in %s" % (expected, utils.secs_to_timestr(self._timeout))) return ret def read_until_regexp(self, *expected): """Reads from the current output, until a match to a regexp in expected. Expected is a list of regular expression patterns as strings, or compiled regular expressions. The keyword returns the text up to and including the first match to any of the regular expressions. If the last argument in `*expected` is a valid log level, it is used as `loglevel` in the keyword `Read`. Examples: | Read Until Regexp | (#|$) | | Read Until Regexp | first_regexp | second_regexp | | Read Until Regexp | some regexp | DEBUG | """ expected = list(expected) if self._is_valid_log_level(expected[-1]): loglevel = expected[-1] expected = expected[:-1] else: loglevel = 'INFO' try: index, _, ret = self.expect(expected, self._timeout) except TypeError: index, ret = -1, '' ret = ret.decode('ASCII', 'ignore') self._log(ret, loglevel) if index == -1: expected = [ exp if isinstance(exp, basestring) else exp.pattern for exp in expected ] raise AssertionError("No match found for %s in %s" % (utils.seq2str(expected, lastsep=' or '), utils.secs_to_timestr(self._timeout))) return ret def read_until_prompt(self, loglevel=None): """Reads from the current output, until a prompt is found. The prompt must have been set, either in the library import or at login time, or by using the `Set Prompt` keyword. See `Read` for more information on `loglevel`. """ if not self._prompt_is_set(): raise RuntimeError('Prompt is not set') prompt, regexp = self._prompt if regexp: return self.read_until_regexp(prompt, loglevel) return self.read_until(prompt, loglevel) def execute_command(self, command, loglevel=None): """Executes given command and reads and returns everything until prompt. This is a convenience keyword; following two are functionally identical: | ${out} = | Execute Command | Some command | | Write | Some command | | ${out} = | Read Until Prompt | This keyword expects a prompt to be set, see `Read Until Prompt` for details. See `Read` for more information on `loglevel`. """ self.write(command, loglevel) return self.read_until_prompt(loglevel) def set_prompt(self, prompt, prompt_is_regexp=False): """Sets the prompt used in this connection to `prompt`. If `prompt_is_regexp` is a non-empty string, the given prompt is considered to be a regular expression. The old prompt is returned and can be used to restore it later. Example: | ${prompt} | ${regexp} = | Set Prompt | $ | | Do Something | | Set Prompt | ${prompt} | ${regexp} | """ old = hasattr(self, '_prompt') and self._prompt or (None, False) if prompt_is_regexp: self._prompt = (re.compile(prompt), True) else: self._prompt = (prompt, False) if old[1]: return old[0].pattern, True return old def _prompt_is_set(self): return self._prompt[0] is not None def set_default_log_level(self, level): """Sets the default log level used by all read keywords. The possible values are TRACE, DEBUG, INFO and WARN. The default is INFO. The old value is returned and can be used to restore it later, similarly as with `Set Timeout`. """ self._is_valid_log_level(level, raise_if_invalid=True) old = self._default_log_level self._default_log_level = level.upper() return old def _log(self, msg, level=None): self._is_valid_log_level(level, raise_if_invalid=True) msg = msg.strip() if level is None: level = self._default_log_level if msg != '': print '*%s* %s' % (level.upper(), msg) def _is_valid_log_level(self, level, raise_if_invalid=False): if level is None: return True if isinstance(level, basestring) and \ level.upper() in ['TRACE', 'DEBUG', 'INFO', 'WARN']: return True if not raise_if_invalid: return False raise AssertionError("Invalid log level '%s'" % level) def _negotiate_echo_on(self, sock, cmd, opt): # This is supposed to turn server side echoing on and turn other options off. if opt == telnetlib.ECHO and cmd in (telnetlib.WILL, telnetlib.WONT): self.sock.sendall(telnetlib.IAC + telnetlib.DO + opt) elif opt != telnetlib.NOOPT: if cmd in (telnetlib.DO, telnetlib.DONT): self.sock.sendall(telnetlib.IAC + telnetlib.WONT + opt) elif cmd in (telnetlib.WILL, telnetlib.WONT): self.sock.sendall(telnetlib.IAC + telnetlib.DONT + opt)
[ [ 1, 0, 0.0308, 0.0019, 0, 0.66, 0, 248, 0, 1, 0, 0, 248, 0, 0 ], [ 1, 0, 0.0327, 0.0019, 0, 0.66, 0.1429, 654, 0, 1, 0, 0, 654, 0, 0 ], [ 1, 0, 0.0346, 0.0019, 0, ...
[ "import telnetlib", "import time", "import re", "import inspect", "from robot.version import get_version", "from robot import utils", "class Telnet:\n\n \"\"\"A test library providing communication over Telnet connections.\n\n `Telnet` is Robot Framework's standard library that makes it\n possi...
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import OperatingSystem OPSYS = OperatingSystem.OperatingSystem() class DeprecatedOperatingSystem: ROBOT_LIBRARY_SCOPE = 'GLOBAL' delete_environment_variable = OPSYS.remove_environment_variable environment_variable_is_set = OPSYS.environment_variable_should_be_set environment_variable_is_not_set = OPSYS.environment_variable_should_not_be_set fail_unless_exists = OPSYS.should_exist fail_if_exists = OPSYS.should_not_exist fail_unless_file_exists = OPSYS.file_should_exist fail_if_file_exists = OPSYS.file_should_not_exist fail_unless_dir_exists = OPSYS.directory_should_exist fail_if_dir_exists = OPSYS.directory_should_not_exist fail_unless_dir_empty = OPSYS.directory_should_be_empty fail_if_dir_empty = OPSYS.directory_should_not_be_empty fail_unless_file_empty = OPSYS.file_should_be_empty fail_if_file_empty = OPSYS.file_should_not_be_empty empty_dir = OPSYS.empty_directory remove_dir = OPSYS.remove_directory copy_dir = OPSYS.copy_directory move_dir = OPSYS.move_directory create_dir = OPSYS.create_directory list_dir = OPSYS.list_directory list_files_in_dir = OPSYS.list_files_in_directory list_dirs_in_dir = OPSYS.list_directories_in_directory count_items_in_dir = OPSYS.count_items_in_directory count_files_in_dir = OPSYS.count_files_in_directory count_dirs_in_dir = OPSYS.count_directories_in_directory
[ [ 1, 0, 0.3333, 0.0208, 0, 0.66, 0, 59, 0, 1, 0, 0, 59, 0, 0 ], [ 14, 0, 0.375, 0.0208, 0, 0.66, 0.5, 308, 3, 0, 0, 0, 59, 10, 1 ], [ 3, 0, 0.7083, 0.6042, 0, 0.66,...
[ "import OperatingSystem", "OPSYS = OperatingSystem.OperatingSystem()", "class DeprecatedOperatingSystem:\n ROBOT_LIBRARY_SCOPE = 'GLOBAL'\n\n delete_environment_variable = OPSYS.remove_environment_variable\n environment_variable_is_set = OPSYS.environment_variable_should_be_set\n environment_variabl...
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import re import fnmatch from robot.utils import asserts import BuiltIn BUILTIN = BuiltIn.BuiltIn() class DeprecatedBuiltIn: ROBOT_LIBRARY_SCOPE = 'GLOBAL' integer = BUILTIN.convert_to_integer float = BUILTIN.convert_to_number string = BUILTIN.convert_to_string boolean = BUILTIN.convert_to_boolean list = BUILTIN.create_list equal = equals = fail_unless_equal = BUILTIN.should_be_equal not_equal = not_equals = fail_if_equal = BUILTIN.should_not_be_equal is_true = fail_unless = BUILTIN.should_be_true is_false = fail_if = BUILTIN.should_not_be_true fail_if_ints_equal = ints_not_equal = BUILTIN.should_not_be_equal_as_integers ints_equal = fail_unless_ints_equal = BUILTIN.should_be_equal_as_integers floats_not_equal = fail_if_floats_equal = BUILTIN.should_not_be_equal_as_numbers floats_equal = fail_unless_floats_equal = BUILTIN.should_be_equal_as_numbers does_not_start = fail_if_starts = BUILTIN.should_not_start_with starts = fail_unless_starts = BUILTIN.should_start_with does_not_end = fail_if_ends = BUILTIN.should_not_end_with ends = fail_unless_ends = BUILTIN.should_end_with does_not_contain = fail_if_contains = BUILTIN.should_not_contain contains = fail_unless_contains = BUILTIN.should_contain does_not_match = fail_if_matches = BUILTIN.should_not_match matches = fail_unless_matches = BUILTIN.should_match does_not_match_regexp = fail_if_regexp_matches = BUILTIN.should_not_match_regexp matches_regexp = fail_unless_regexp_matches = BUILTIN.should_match_regexp noop = BUILTIN.no_operation set_ = BUILTIN.set_variable message = BUILTIN.comment variable_exists = fail_unless_variable_exists = BUILTIN.variable_should_exist variable_does_not_exist = fail_if_variable_exists = BUILTIN.variable_should_not_exist def error(self, msg=None): """Errors the test immediately with the given message.""" asserts.error(msg) def grep(self, text, pattern, pattern_type='literal string'): lines = self._filter_lines(text.splitlines(), pattern, pattern_type) return '\n'.join(lines) def _filter_lines(self, lines, pattern, ptype): ptype = ptype.lower().replace(' ','').replace('-','') if not pattern: filtr = lambda line: True elif 'simple' in ptype or 'glob' in ptype: if 'caseinsensitive' in ptype: pattern = pattern.lower() filtr = lambda line: fnmatch.fnmatchcase(line.lower(), pattern) else: filtr = lambda line: fnmatch.fnmatchcase(line, pattern) elif 'regularexpression' in ptype or 'regexp' in ptype: pattern = re.compile(pattern) filtr = lambda line: pattern.search(line) elif 'caseinsensitive' in ptype: pattern = pattern.lower() filtr = lambda line: pattern in line.lower() else: filtr = lambda line: pattern in line return [ line for line in lines if filtr(line) ]
[ [ 1, 0, 0.1798, 0.0112, 0, 0.66, 0, 540, 0, 1, 0, 0, 540, 0, 0 ], [ 1, 0, 0.191, 0.0112, 0, 0.66, 0.2, 626, 0, 1, 0, 0, 626, 0, 0 ], [ 1, 0, 0.2247, 0.0112, 0, 0.66...
[ "import re", "import fnmatch", "from robot.utils import asserts", "import BuiltIn", "BUILTIN = BuiltIn.BuiltIn()", "class DeprecatedBuiltIn:\n ROBOT_LIBRARY_SCOPE = 'GLOBAL'\n\n integer = BUILTIN.convert_to_integer\n float = BUILTIN.convert_to_number\n string = BUILTIN.convert_to_string\n b...
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import re from fnmatch import fnmatchcase from random import randint from string import ascii_lowercase, ascii_uppercase, digits from robot.version import get_version class String: """A test library for string manipulation and verification. `String` is Robot Framework's standard library for manipulating strings (e.g. `Replace String Using Regexp`, `Split To Lines`) and verifying their contents (e.g. `Should Be String`). Following keywords from the BuiltIn library can also be used with strings: - `Catenate` - `Get Length` - `Length Should Be` - `Should (Not) Match (Regexp)` - `Should (Not) Be Empty` - `Should (Not) Be Equal (As Strings/Integers/Numbers)` - `Should (Not) Contain` - `Should (Not) Start With` - `Should (Not) End With` """ ROBOT_LIBRARY_SCOPE = 'GLOBAL' ROBOT_LIBRARY_VERSION = get_version() def get_line_count(self, string): """Returns and logs the number of lines in the given `string`.""" count = len(string.splitlines()) print '*INFO* %d lines' % count return count def split_to_lines(self, string, start=0, end=None): """Converts the `string` into a list of lines. It is possible to get only a selection of lines from `start` to `end` so that `start` index is inclusive and `end` is exclusive. Line numbering starts from 0, and it is possible to use negative indices to refer to lines from the end. Lines are returned without the newlines. The number of returned lines is automatically logged. Examples: | @{lines} = | Split To Lines | ${manylines} | | | | @{ignore first} = | Split To Lines | ${manylines} | 1 | | | @{ignore last} = | Split To Lines | ${manylines} | | -1 | | @{5th to 10th} = | Split To Lines | ${manylines} | 4 | 10 | | @{first two} = | Split To Lines | ${manylines} | | 1 | | @{last two} = | Split To Lines | ${manylines} | -2 | | Use `Get Line` if you only need to get a single line. """ start = self._convert_to_index(start, 'start') end = self._convert_to_index(end, 'end') lines = string.splitlines()[start:end] print '*INFO* %d lines returned' % len(lines) return lines def get_line(self, string, line_number): """Returns the specified line from the given `string`. Line numbering starts from 0 and it is possible to use negative indices to refer to lines from the end. The line is returned without the newline character. Examples: | ${first} = | Get Line | ${string} | 0 | | ${2nd last} = | Get Line | ${string} | -2 | """ line_number = self._convert_to_integer(line_number, 'line_number') return string.splitlines()[line_number] def get_lines_containing_string(self, string, pattern, case_insensitive=False): """Returns lines of the given `string` that contain the `pattern`. The `pattern` is always considered to be a normal string and a line matches if the `pattern` is found anywhere in it. By default the match is case-sensitive, but setting `case_insensitive` to any value makes it case-insensitive. Lines are returned as one string catenated back together with newlines. Possible trailing newline is never returned. The number of matching lines is automatically logged. Examples: | ${lines} = | Get Lines Containing String | ${result} | An example | | ${ret} = | Get Lines Containing String | ${ret} | FAIL | case-insensitive | See `Get Lines Matching Pattern` and `Get Lines Matching Regexp` if you need more complex pattern matching. """ if case_insensitive: pattern = pattern.lower() contains = lambda line: pattern in line.lower() else: contains = lambda line: pattern in line return self._get_matching_lines(string, contains) def get_lines_matching_pattern(self, string, pattern, case_insensitive=False): """Returns lines of the given `string` that match the `pattern`. The `pattern` is a _glob pattern_ where: | * | matches everything | | ? | matches any single character | | [chars] | matches any character inside square brackets (e.g. '[abc]' matches either 'a', 'b' or 'c') | | [!chars] | matches any character not inside square brackets | A line matches only if it matches the `pattern` fully. By default the match is case-sensitive, but setting `case_insensitive` to any value makes it case-insensitive. Lines are returned as one string catenated back together with newlines. Possible trailing newline is never returned. The number of matching lines is automatically logged. Examples: | ${lines} = | Get Lines Matching Pattern | ${result} | Wild???? example | | ${ret} = | Get Lines Matching Pattern | ${ret} | FAIL: * | case-insensitive | See `Get Lines Matching Regexp` if you need more complex patterns and `Get Lines Containing String` if searching literal strings is enough. """ if case_insensitive: pattern = pattern.lower() matches = lambda line: fnmatchcase(line.lower(), pattern) else: matches = lambda line: fnmatchcase(line, pattern) return self._get_matching_lines(string, matches) def get_lines_matching_regexp(self, string, pattern): """Returns lines of the given `string` that match the regexp `pattern`. See `BuiltIn.Should Match Regexp` for more information about Python regular expression syntax in general and how to use it in Robot Framework test data in particular. A line matches only if it matches the `pattern` fully. Notice that to make the match case-insensitive, you need to embed case-insensitive flag into the pattern. Lines are returned as one string catenated back together with newlines. Possible trailing newline is never returned. The number of matching lines is automatically logged. Examples: | ${lines} = | Get Lines Matching Regexp | ${result} | Reg\\\\w{3} example | | ${ret} = | Get Lines Matching Regexp | ${ret} | (?i)FAIL: .* | See `Get Lines Matching Pattern` and `Get Lines Containing String` if you do not need full regular expression powers (and complexity). """ regexp = re.compile('^%s$' % pattern) return self._get_matching_lines(string, regexp.match) def _get_matching_lines(self, string, matches): lines = string.splitlines() matching = [ line for line in lines if matches(line) ] print '*INFO* %d out of %d lines matched' % (len(matching), len(lines)) return '\n'.join(matching) def replace_string(self, string, search_for, replace_with, count=-1): """Replaces `search_for` in the given `string` with `replace_with`. `search_for` is used as a literal string. See `Replace String Using Regexp` if more powerful pattern matching is needed. If the optional argument `count` is given, only that many occurrences from left are replaced. Negative `count` means that all occurrences are replaced (default behaviour) and zero means that nothing is done. A modified version of the string is returned and the original string is not altered. Examples: | ${str} = | Replace String | ${str} | Hello | Hi | | | ${str} = | Replace String | ${str} | world | tellus | 1 | """ count = self._convert_to_integer(count, 'count') return string.replace(search_for, replace_with, count) def replace_string_using_regexp(self, string, pattern, replace_with, count=-1): """Replaces `pattern` in the given `string` with `replace_with`. This keyword is otherwise identical to `Replace String`, but the `pattern` to search for is considered to be a regular expression. See `BuiltIn.Should Match Regexp` for more information about Python regular expression syntax in general and how to use it in Robot Framework test data in particular. Examples: | ${str} = | Replace String Using Regexp | ${str} | (Hello|Hi) | Hei | | | ${str} = | Replace String Using Regexp | ${str} | 20\\\\d\\\\d-\\\\d\\\\d-\\\\d\\\\d | <DATE> | 2 | """ count = self._convert_to_integer(count, 'count') # re.sub handles 0 and negative counts differently than string.replace if count < 0: count = 0 elif count == 0: count = -1 return re.sub(pattern, replace_with, string, count) def split_string(self, string, separator=None, max_split=-1): """Splits the `string` using `separator` as a delimiter string. If a `separator` is not given, any whitespace string is a separator. In that case also possible consecutive whitespace as well as leading and trailing whitespace is ignored. Split words are returned as a list. If the optional `max_split` is given, at most `max_split` splits are done, and the returned list will have maximum `max_split + 1` elements. Examples: | @{words} = | Split String | ${string} | | @{words} = | Split String | ${string} | ,${SPACE} | | ${pre} | ${post} = | Split String | ${string} | :: | 1 | See `Split String From Right` if you want to start splitting from right, and `Fetch From Left` and `Fetch From Right` if you only want to get first/last part of the string. """ if separator == '': separator = None max_split = self._convert_to_integer(max_split, 'max_split') return string.split(separator, max_split) def split_string_from_right(self, string, separator=None, max_split=-1): """Splits the `string` using `separator` starting from right. Same as `Split String`, but splitting is started from right. This has an effect only when `max_split` is given. Examples: | ${first} | ${others} = | Split String | ${string} | - | 1 | | ${others} | ${last} = | Split String From Right | ${string} | - | 1 | """ # Strings in Jython 2.2 don't have 'rsplit' methods reversed = self.split_string(string[::-1], separator, max_split) return [ r[::-1] for r in reversed ][::-1] def fetch_from_left(self, string, marker): """Returns contents of the `string` before the first occurrence of `marker`. If the `marker` is not found, whole string is returned. See also `Fetch From Right`, `Split String` and `Split String From Right`. """ return string.split(marker)[0] def fetch_from_right(self, string, marker): """Returns contents of the `string` after the last occurrence of `marker`. If the `marker` is not found, whole string is returned. See also `Fetch From Left`, `Split String` and `Split String From Right`. """ return string.split(marker)[-1] def generate_random_string(self, length=8, chars='[LETTERS][NUMBERS]'): """Generates a string with a desired `length` from the given `chars`. The population sequence `chars` contains the characters to use when generating the random string. It can contain any characters, and it is possible to use special markers explained in the table below: | _[LOWER]_ | Lowercase ASCII characters from 'a' to 'z'. | | _[UPPER]_ | Uppercase ASCII characters from 'A' to 'Z'. | | _[LETTERS]_ | Lowercase and uppercase ASCII characters. | | _[NUMBERS]_ | Numbers from 0 to 9. | Examples: | ${ret} = | Generate Random String | | ${low} = | Generate Random String | 12 | [LOWER] | | ${bin} = | Generate Random String | 8 | 01 | | ${hex} = | Generate Random String | 4 | [NUMBERS]abcdef | """ if length == '': length = 8 length = self._convert_to_integer(length, 'length') for name, value in [('[LOWER]', ascii_lowercase), ('[UPPER]', ascii_uppercase), ('[LETTERS]', ascii_lowercase + ascii_uppercase), ('[NUMBERS]', digits)]: chars = chars.replace(name, value) maxi = len(chars) - 1 return ''.join([ chars[randint(0, maxi)] for i in xrange(length) ]) def get_substring(self, string, start, end=None): """Returns a substring from `start` index to `end` index. The `start` index is inclusive and `end` is exclusive. Indexing starts from 0, and it is possible to use negative indices to refer to characters from the end. Examples: | ${ignore first} = | Get Substring | ${string} | 1 | | | ${ignore last} = | Get Substring | ${string} | | -1 | | ${5th to 10th} = | Get Substring | ${string} | 4 | 10 | | ${first two} = | Get Substring | ${string} | | 1 | | ${last two} = | Get Substring | ${string} | -2 | | """ start = self._convert_to_index(start, 'start') end = self._convert_to_index(end, 'end') return string[start:end] def should_be_string(self, item, msg=None): """Fails if the given `item` is not a string. The default error message can be overridden with the optional `msg` argument. """ if not isinstance(item, basestring): if not msg: msg = "Given item '%s' is not a string" % item raise AssertionError(msg) def should_not_be_string(self, item, msg=None): """Fails if the given `item` is a string. The default error message can be overridden with the optional `msg` argument. """ if isinstance(item, basestring): if not msg: msg = "Given item '%s' is a string" % item raise AssertionError(msg) def should_be_lowercase(self, string, msg=None): """Fails if the given `string` is not in lowercase. The default error message can be overridden with the optional `msg` argument. For example 'string' and 'with specials!' would pass, and 'String', '' and ' ' would fail. See also `Should Be Uppercase` and `Should Be Titlecase`. All these keywords were added in Robot Framework 2.1.2. """ if not string.islower(): raise AssertionError(msg or "'%s' is not lowercase" % string) def should_be_uppercase(self, string, msg=None): """Fails if the given `string` is not in uppercase. The default error message can be overridden with the optional `msg` argument. For example 'STRING' and 'WITH SPECIALS!' would pass, and 'String', '' and ' ' would fail. See also `Should Be Titlecase` and `Should Be Lowercase`. All these keywords were added in Robot Framework 2.1.2. """ if not string.isupper(): raise AssertionError(msg or "'%s' is not uppercase" % string) def should_be_titlecase(self, string, msg=None): """Fails if given `string` is not title. `string` is a titlecased string if there is at least one character in it, uppercase characters only follow uncased characters and lowercase characters only cased ones. The default error message can be overridden with the optional `msg` argument. For example 'This Is Title' would pass, and 'Word In UPPER', 'Word In lower', '' and ' ' would fail. See also `Should Be Uppercase` and `Should Be Lowercase`. All theses keyword were added in Robot Framework 2.1.2. """ if not string.istitle(): raise AssertionError(msg or "'%s' is not titlecase" % string) def _convert_to_index(self, value, name): if value == '': return 0 if value is None: return None return self._convert_to_integer(value, name) def _convert_to_integer(self, value, name): try: return int(value) except ValueError: raise ValueError("Cannot convert '%s' argument '%s' to an integer" % (name, value))
[ [ 1, 0, 0.0385, 0.0024, 0, 0.66, 0, 540, 0, 1, 0, 0, 540, 0, 0 ], [ 1, 0, 0.0409, 0.0024, 0, 0.66, 0.2, 626, 0, 1, 0, 0, 626, 0, 0 ], [ 1, 0, 0.0433, 0.0024, 0, 0.6...
[ "import re", "from fnmatch import fnmatchcase", "from random import randint", "from string import ascii_lowercase, ascii_uppercase, digits", "from robot.version import get_version", "class String:\n\n \"\"\"A test library for string manipulation and verification.\n\n `String` is Robot Framework's st...
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.
[]
[]
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. class Populator(object): """Explicit interface for all populators.""" def add(self, row): raise NotImplementedError() def populate(self): raise NotImplementedError() class CommentCacher(object): def __init__(self): self._init_comments() def _init_comments(self): self._comments = [] def add(self, comment): self._comments.append(comment) def consume_comments_with(self, function): for c in self._comments: function(c) self._init_comments() class _TablePopulator(Populator): def __init__(self, table): self._table = table self._populator = NullPopulator() self._comments = CommentCacher() def add(self, row): if self._is_cacheable_comment_row(row): self._comments.add(row) else: self._add(row) def _add(self, row): if not self._is_continuing(row): self._populator.populate() self._populator = self._get_populator(row) self._comments.consume_comments_with(self._populator.add) self._populator.add(row) def populate(self): self._comments.consume_comments_with(self._populator.add) self._populator.populate() def _is_continuing(self, row): return row.is_continuing() and self._populator def _is_cacheable_comment_row(self, row): return row.is_commented() class SettingTablePopulator(_TablePopulator): def _get_populator(self, row): row.handle_old_style_metadata() setter = self._table.get_setter(row.head) return SettingPopulator(setter) if setter else NullPopulator() class VariableTablePopulator(_TablePopulator): def _get_populator(self, row): return VariablePopulator(self._table.add, row.head) class _StepContainingTablePopulator(_TablePopulator): def _is_continuing(self, row): return row.is_indented() and self._populator or row.is_commented() def _is_cacheable_comment_row(self, row): return row.is_commented() and isinstance(self._populator, NullPopulator) class TestTablePopulator(_StepContainingTablePopulator): def _get_populator(self, row): return TestCasePopulator(self._table.add) class KeywordTablePopulator(_StepContainingTablePopulator): def _get_populator(self, row): return UserKeywordPopulator(self._table.add) class ForLoopPopulator(Populator): def __init__(self, for_loop_creator): self._for_loop_creator = for_loop_creator self._loop = None self._populator = NullPopulator() self._declaration = [] def add(self, row): dedented_row = row.dedent() if not self._loop: declaration_ready = self._populate_declaration(row) if not declaration_ready: return self._loop = self._for_loop_creator(self._declaration) if not row.is_continuing(): self._populator.populate() self._populator = StepPopulator(self._loop.add_step) self._populator.add(dedented_row) def _populate_declaration(self, row): if row.starts_for_loop() or row.is_continuing(): self._declaration.extend(row.dedent().data) return False return True def populate(self): if not self._loop: self._for_loop_creator(self._declaration) self._populator.populate() class _TestCaseUserKeywordPopulator(Populator): def __init__(self, test_or_uk_creator): self._test_or_uk_creator = test_or_uk_creator self._test_or_uk = None self._populator = NullPopulator() self._comments = CommentCacher() def add(self, row): if row.is_commented(): self._comments.add(row) return if not self._test_or_uk: self._test_or_uk = self._test_or_uk_creator(row.head) dedented_row = row.dedent() if dedented_row: self._handle_data_row(dedented_row) def _handle_data_row(self, row): if not self._continues(row): self._populator.populate() self._populator = self._get_populator(row) self._flush_comments_with(self._populate_comment_row) else: self._flush_comments_with(self._populator.add) self._populator.add(row) def _populate_comment_row(self, crow): populator = StepPopulator(self._test_or_uk.add_step) populator.add(crow) populator.populate() def _flush_comments_with(self, function): self._comments.consume_comments_with(function) def populate(self): self._populator.populate() self._flush_comments_with(self._populate_comment_row) def _get_populator(self, row): if row.starts_test_or_user_keyword_setting(): setter = self._setting_setter(row) return SettingPopulator(setter) if setter else NullPopulator() if row.starts_for_loop(): return ForLoopPopulator(self._test_or_uk.add_for_loop) return StepPopulator(self._test_or_uk.add_step) def _continues(self, row): return row.is_continuing() and self._populator or \ (isinstance(self._populator, ForLoopPopulator) and row.is_indented()) def _setting_setter(self, row): setting_name = row.test_or_user_keyword_setting_name() return self._test_or_uk.get_setter(setting_name) class TestCasePopulator(_TestCaseUserKeywordPopulator): _item_type = 'test case' class UserKeywordPopulator(_TestCaseUserKeywordPopulator): _item_type = 'keyword' class Comments(object): def __init__(self): self._crows = [] def add(self, row): if row.comments: self._crows.append(row.comments) def formatted_value(self): rows = (' '.join(row).strip() for row in self._crows) return '\n'.join(rows) class _PropertyPopulator(Populator): def __init__(self, setter): self._setter = setter self._value = [] self._comments = Comments() def add(self, row): if not row.is_commented(): self._add(row) self._comments.add(row) def _add(self, row): self._value.extend(row.dedent().data) class VariablePopulator(_PropertyPopulator): def __init__(self, setter, name): _PropertyPopulator.__init__(self, setter) self._name = name def populate(self): self._setter(self._name, self._value, self._comments.formatted_value()) class SettingPopulator(_PropertyPopulator): def populate(self): self._setter(self._value, self._comments.formatted_value()) class StepPopulator(_PropertyPopulator): def _add(self, row): self._value.extend(row.data) def populate(self): if self._value or self._comments: self._setter(self._value, self._comments.formatted_value()) class NullPopulator(Populator): def add(self, row): pass def populate(self): pass def __nonzero__(self): return False
[ [ 3, 0, 0.067, 0.0153, 0, 0.66, 0, 532, 0, 2, 0, 0, 186, 0, 2 ], [ 8, 1, 0.0651, 0.0038, 1, 0.48, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 2, 1, 0.069, 0.0038, 1, 0.48, 0...
[ "class Populator(object):\n \"\"\"Explicit interface for all populators.\"\"\"\n def add(self, row): raise NotImplementedError()\n def populate(self): raise NotImplementedError()", " \"\"\"Explicit interface for all populators.\"\"\"", " def add(self, row): raise NotImplementedError()", " de...
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os from robot.errors import DataError from robot.variables import is_var from robot.output import LOGGER from robot import utils from settings import (Documentation, Fixture, Timeout, Tags, Metadata, Library, Resource, Variables, Arguments, Return, Template) from populators import FromFilePopulator, FromDirectoryPopulator def TestData(parent=None, source=None, include_suites=[], warn_on_skipped=False): if os.path.isdir(source): return TestDataDirectory(parent, source, include_suites, warn_on_skipped) return TestCaseFile(parent, source) class _TestData(object): def __init__(self, parent=None, source=None): self.parent = parent self.source = utils.abspath(source) if source else None self.children = [] self._tables = None def _get_tables(self): if not self._tables: self._tables = utils.NormalizedDict({'Setting': self.setting_table, 'Settings': self.setting_table, 'Metadata': self.setting_table, 'Variable': self.variable_table, 'Variables': self.variable_table, 'Keyword': self.keyword_table, 'Keywords': self.keyword_table, 'User Keyword': self.keyword_table, 'User Keywords': self.keyword_table, 'Test Case': self.testcase_table, 'Test Cases': self.testcase_table}) return self._tables def start_table(self, header_row): table_name = header_row[0] try: table = self._valid_table(self._get_tables()[table_name]) except KeyError: return None else: if table is not None: table.set_header(header_row) return table @property def name(self): if not self.source: return None name = self._get_basename() name = name.split('__', 1)[-1] # Strip possible prefix name = name.replace('_', ' ').strip() if name.islower(): name = name.title() return name def _get_basename(self): return os.path.splitext(os.path.basename(self.source))[0] @property def keywords(self): return self.keyword_table.keywords @property def imports(self): return self.setting_table.imports def report_invalid_syntax(self, table, message, level='ERROR'): initfile = getattr(self, 'initfile', None) path = os.path.join(self.source, initfile) if initfile else self.source LOGGER.write("Invalid syntax in file '%s' in table '%s': %s" % (path, table, message), level) class TestCaseFile(_TestData): def __init__(self, parent=None, source=None): _TestData.__init__(self, parent, source) self.directory = os.path.dirname(self.source) if self.source else None self.setting_table = TestCaseFileSettingTable(self) self.variable_table = VariableTable(self) self.testcase_table = TestCaseTable(self) self.keyword_table = KeywordTable(self) if source: # FIXME: model should be decoupled from populating FromFilePopulator(self).populate(source) self._validate() def _validate(self): if not self.testcase_table.is_started(): raise DataError('File has no test case table.') def _valid_table(self, table): return table def has_tests(self): return True def __iter__(self): for table in [self.setting_table, self.variable_table, self.testcase_table, self.keyword_table]: yield table class ResourceFile(_TestData): def __init__(self, source=None): _TestData.__init__(self, source=source) self.directory = os.path.dirname(self.source) if self.source else None self.setting_table = ResourceFileSettingTable(self) self.variable_table = VariableTable(self) self.testcase_table = TestCaseTable(self) self.keyword_table = KeywordTable(self) if self.source: FromFilePopulator(self).populate(source) self._report_status() def _report_status(self): if self.setting_table or self.variable_table or self.keyword_table: LOGGER.info("Imported resource file '%s' (%d keywords)." % (self.source, len(self.keyword_table.keywords))) else: LOGGER.warn("Imported resource file '%s' is empty." % self.source) def _valid_table(self, table): if table is self.testcase_table: raise DataError("Resource file '%s' contains a test case table " "which is not allowed." % self.source) return table def __iter__(self): for table in [self.setting_table, self.variable_table, self.keyword_table]: yield table class TestDataDirectory(_TestData): def __init__(self, parent=None, source=None, include_suites=[], warn_on_skipped=False): _TestData.__init__(self, parent, source) self.directory = self.source self.initfile = None self.setting_table = InitFileSettingTable(self) self.variable_table = VariableTable(self) self.testcase_table = TestCaseTable(self) self.keyword_table = KeywordTable(self) if self.source: FromDirectoryPopulator().populate(self.source, self, include_suites, warn_on_skipped) self.children = [ ch for ch in self.children if ch.has_tests() ] def _get_basename(self): return os.path.basename(self.source) def _valid_table(self, table): if table is self.testcase_table: LOGGER.error("Test suite init file in '%s' contains a test case " "table which is not allowed." % self.source) return None return table def add_child(self, path, include_suites): self.children.append(TestData(parent=self,source=path, include_suites=include_suites)) def has_tests(self): return any(ch.has_tests() for ch in self.children) def __iter__(self): for table in [self.setting_table, self.variable_table, self.keyword_table]: yield table class _Table(object): def __init__(self, parent): self.parent = parent self.header = None def set_header(self, header): self.header = header @property def name(self): return self.header[0] @property def source(self): return self.parent.source @property def directory(self): return self.parent.directory def report_invalid_syntax(self, message, level='ERROR'): self.parent.report_invalid_syntax(self.name, message, level) class _WithSettings(object): def get_setter(self, setting_name): normalized = self.normalize(setting_name) if normalized in self._setters: return self._setters[normalized](self) self.report_invalid_syntax("Non-existing setting '%s'." % setting_name) def is_setting(self, setting_name): return self.normalize(setting_name) in self._setters def normalize(self, setting): result = utils.normalize(setting) return result[0:-1] if result and result[-1]==':' else result class _SettingTable(_Table, _WithSettings): type = 'setting' def __init__(self, parent): _Table.__init__(self, parent) self.doc = Documentation('Documentation', self) self.suite_setup = Fixture('Suite Setup', self) self.suite_teardown = Fixture('Suite Teardown', self) self.test_setup = Fixture('Test Setup', self) self.test_teardown = Fixture('Test Teardown', self) self.force_tags = Tags('Force Tags', self) self.default_tags = Tags('Default Tags', self) self.test_template = Template('Test Template', self) self.test_timeout = Timeout('Test Timeout', self) self.metadata = [] self.imports = [] def _get_adder(self, adder_method): def adder(value, comment): name = value[0] if value else '' adder_method(name, value[1:], comment) return adder def add_metadata(self, name, value='', comment=None): self.metadata.append(Metadata('Metadata', self, name, value, comment)) return self.metadata[-1] def add_library(self, name, args=None, comment=None): self.imports.append(Library(self, name, args, comment=comment)) return self.imports[-1] def add_resource(self, name, invalid_args=None, comment=None): self.imports.append(Resource(self, name, invalid_args, comment=comment)) return self.imports[-1] def add_variables(self, name, args=None, comment=None): self.imports.append(Variables(self, name, args, comment=comment)) return self.imports[-1] def __nonzero__(self): return any(setting.is_set() for setting in self) class TestCaseFileSettingTable(_SettingTable): _setters = {'documentation': lambda s: s.doc.populate, 'document': lambda s: s.doc.populate, 'suitesetup': lambda s: s.suite_setup.populate, 'suiteprecondition': lambda s: s.suite_setup.populate, 'suiteteardown': lambda s: s.suite_teardown.populate, 'suitepostcondition': lambda s: s.suite_teardown.populate, 'testsetup': lambda s: s.test_setup.populate, 'testprecondition': lambda s: s.test_setup.populate, 'testteardown': lambda s: s.test_teardown.populate, 'testpostcondition': lambda s: s.test_teardown.populate, 'forcetags': lambda s: s.force_tags.populate, 'defaulttags': lambda s: s.default_tags.populate, 'testtemplate': lambda s: s.test_template.populate, 'testtimeout': lambda s: s.test_timeout.populate, 'library': lambda s: s._get_adder(s.add_library), 'resource': lambda s: s._get_adder(s.add_resource), 'variables': lambda s: s._get_adder(s.add_variables), 'metadata': lambda s: s._get_adder(s.add_metadata)} def __iter__(self): for setting in [self.doc, self.suite_setup, self.suite_teardown, self.test_setup, self.test_teardown, self.force_tags, self.default_tags, self.test_template, self.test_timeout] \ + self.metadata + self.imports: yield setting class ResourceFileSettingTable(_SettingTable): _setters = {'documentation': lambda s: s.doc.populate, 'document': lambda s: s.doc.populate, 'library': lambda s: s._get_adder(s.add_library), 'resource': lambda s: s._get_adder(s.add_resource), 'variables': lambda s: s._get_adder(s.add_variables)} def __iter__(self): for setting in [self.doc] + self.imports: yield setting class InitFileSettingTable(_SettingTable): _setters = {'documentation': lambda s: s.doc.populate, 'document': lambda s: s.doc.populate, 'suitesetup': lambda s: s.suite_setup.populate, 'suiteprecondition': lambda s: s.suite_setup.populate, 'suiteteardown': lambda s: s.suite_teardown.populate, 'suitepostcondition': lambda s: s.suite_teardown.populate, 'testsetup': lambda s: s.test_setup.populate, 'testprecondition': lambda s: s.test_setup.populate, 'testteardown': lambda s: s.test_teardown.populate, 'testpostcondition': lambda s: s.test_teardown.populate, 'forcetags': lambda s: s.force_tags.populate, 'library': lambda s: s._get_adder(s.add_library), 'resource': lambda s: s._get_adder(s.add_resource), 'variables': lambda s: s._get_adder(s.add_variables), 'metadata': lambda s: s._get_adder(s.add_metadata)} def __iter__(self): for setting in [self.doc, self.suite_setup, self.suite_teardown, self.test_setup, self.test_teardown, self.force_tags] \ + self.metadata + self.imports: yield setting class VariableTable(_Table): type = 'variable' def __init__(self, parent): _Table.__init__(self, parent) self.variables = [] def add(self, name, value, comment=None): self.variables.append(Variable(name, value, comment)) def __iter__(self): return iter(self.variables) def __nonzero__(self): return bool(self.variables) class TestCaseTable(_Table): type = 'testcase' def __init__(self, parent): _Table.__init__(self, parent) self.tests = [] def add(self, name): self.tests.append(TestCase(self, name)) return self.tests[-1] def __iter__(self): return iter(self.tests) def __nonzero__(self): return bool(self.tests) def is_started(self): return bool(self.header) class KeywordTable(_Table): type = 'keyword' def __init__(self, parent): _Table.__init__(self, parent) self.keywords = [] def add(self, name): self.keywords.append(UserKeyword(self, name)) return self.keywords[-1] def __iter__(self): return iter(self.keywords) def __nonzero__(self): return bool(self.keywords) class Variable(object): def __init__(self, name, value, comment=None): self.name = name.rstrip('= ') if name.startswith('$') and value == []: value = '' if isinstance(value, basestring): value = [value] # Need to support scalar lists until RF 2.6 self.value = value self.comment = comment def as_list(self): ret = [self.name] + self.value if self.comment: ret.append('# %s' % self.comment) return ret def is_set(self): return True def is_for_loop(self): return False class _WithSteps(object): def add_step(self, content, comment=None): self.steps.append(Step(content, comment)) return self.steps[-1] class TestCase(_WithSteps, _WithSettings): def __init__(self, parent, name): self.parent = parent self.name = name self.doc = Documentation('[Documentation]', self) self.template = Template('[Template]', self) self.tags = Tags('[Tags]', self) self.setup = Fixture('[Setup]', self) self.teardown = Fixture('[Teardown]', self) self.timeout = Timeout('[Timeout]', self) self.steps = [] _setters = {'documentation': lambda s: s.doc.populate, 'document': lambda s: s.doc.populate, 'template': lambda s: s.template.populate, 'setup': lambda s: s.setup.populate, 'precondition': lambda s: s.setup.populate, 'teardown': lambda s: s.teardown.populate, 'postcondition': lambda s: s.teardown.populate, 'tags': lambda s: s.tags.populate, 'timeout': lambda s: s.timeout.populate} @property def source(self): return self.parent.source @property def directory(self): return self.parent.directory def add_for_loop(self, data): self.steps.append(ForLoop(data)) return self.steps[-1] def report_invalid_syntax(self, message, level='ERROR'): type_ = 'test case' if type(self) is TestCase else 'keyword' message = "Invalid syntax in %s '%s': %s" % (type_, self.name, message) self.parent.report_invalid_syntax(message, level) def __iter__(self): for element in [self.doc, self.tags, self.setup, self.template, self.timeout] \ + self.steps + [self.teardown]: yield element class UserKeyword(TestCase): def __init__(self, parent, name): self.parent = parent self.name = name self.doc = Documentation('[Documentation]', self) self.args = Arguments('[Arguments]', self) self.return_ = Return('[Return]', self) self.timeout = Timeout('[Timeout]', self) self.teardown = Fixture('[Teardown]', self) self.steps = [] _setters = {'documentation': lambda s: s.doc.populate, 'document': lambda s: s.doc.populate, 'arguments': lambda s: s.args.populate, 'return': lambda s: s.return_.populate, 'timeout': lambda s: s.timeout.populate, 'teardown': lambda s: s.teardown.populate} def __iter__(self): for element in [self.args, self.doc, self.timeout] \ + self.steps + [self.teardown, self.return_]: yield element class ForLoop(_WithSteps): def __init__(self, content): self.range, index = self._get_range_and_index(content) self.vars = content[:index] self.items = content[index+1:] self.steps = [] def _get_range_and_index(self, content): for index, item in enumerate(content): item = item.upper().replace(' ', '') if item in ['IN', 'INRANGE']: return item == 'INRANGE', index return False, len(content) def is_comment(self): return False def is_for_loop(self): return True def apply_template(self, template): return self def as_list(self): return [': FOR'] + self.vars + ['IN RANGE' if self.range else 'IN'] + self.items def __iter__(self): return iter(self.steps) class Step(object): def __init__(self, content, comment=None): self.assign = self._get_assigned_vars(content) try: self.keyword = content[len(self.assign)] except IndexError: self.keyword = None self.args = content[len(self.assign)+1:] self.comment = comment def _get_assigned_vars(self, content): vars = [] for item in content: if not is_var(item.rstrip('= ')): break vars.append(item) return vars def is_comment(self): return not (self.assign or self.keyword or self.args) def is_for_loop(self): return False def apply_template(self, template): if self.is_comment(): return self return Step([template] + self.as_list(include_comment=False)) def is_set(self): return True def as_list(self, indent=False, include_comment=True): kw = [self.keyword] if self.keyword is not None else [] ret = self.assign + kw + self.args if indent: ret.insert(0, '') if include_comment and self.comment: ret.append('# %s' % self.comment) return ret
[ [ 1, 0, 0.0261, 0.0017, 0, 0.66, 0, 688, 0, 1, 0, 0, 688, 0, 0 ], [ 1, 0, 0.0296, 0.0017, 0, 0.66, 0.0385, 299, 0, 1, 0, 0, 299, 0, 0 ], [ 1, 0, 0.0313, 0.0017, 0, ...
[ "import os", "from robot.errors import DataError", "from robot.variables import is_var", "from robot.output import LOGGER", "from robot import utils", "from settings import (Documentation, Fixture, Timeout, Tags, Metadata,\n Library, Resource, Variables, Arguments, Return, Template)",...
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import re from tsvreader import TsvReader class TxtReader(TsvReader): _space_splitter = re.compile(' {2,}') _pipe_splitter = re.compile(' \|(?= )') def _split_row(self, row): row = row.rstrip().replace('\t', ' ') if not row.startswith('| '): return self._space_splitter.split(row) if row.endswith(' |'): row = row[1:-1] else: row = row[1:] return self._pipe_splitter.split(row) def _process(self, cell): return cell.decode('UTF-8')
[ [ 1, 0, 0.4167, 0.0278, 0, 0.66, 0, 540, 0, 1, 0, 0, 540, 0, 0 ], [ 1, 0, 0.4722, 0.0278, 0, 0.66, 0.5, 276, 0, 1, 0, 0, 276, 0, 0 ], [ 3, 0, 0.7778, 0.4722, 0, 0.6...
[ "import re", "from tsvreader import TsvReader", "class TxtReader(TsvReader):\n\n _space_splitter = re.compile(' {2,}')\n _pipe_splitter = re.compile(' \\|(?= )')\n\n def _split_row(self, row):\n row = row.rstrip().replace('\\t', ' ')\n if not row.startswith('| '):", " _space_splitte...
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from codecs import BOM_UTF8 class TsvReader: def read(self, tsvfile, populator): process = False for index, row in enumerate(tsvfile.readlines()): if index == 0 and row.startswith(BOM_UTF8): row = row[len(BOM_UTF8):] cells = [ self._process(cell) for cell in self._split_row(row) ] name = cells and cells[0].strip() or '' if name.startswith('*') and populator.start_table([ c.replace('*','') for c in cells ]): process = True elif process: populator.add(cells) populator.eof() def _split_row(self, row): return row.rstrip().split('\t') def _process(self, cell): if len(cell) > 1 and cell[0] == cell[-1] == '"': cell = cell[1:-1].replace('""','"') return cell.decode('UTF-8')
[ [ 1, 0, 0.3846, 0.0256, 0, 0.66, 0, 220, 0, 1, 0, 0, 220, 0, 0 ], [ 3, 0, 0.7308, 0.5641, 0, 0.66, 1, 619, 0, 3, 0, 0, 0, 0, 17 ], [ 2, 1, 0.6538, 0.3077, 1, 0.81, ...
[ "from codecs import BOM_UTF8", "class TsvReader:\n\n def read(self, tsvfile, populator):\n process = False\n for index, row in enumerate(tsvfile.readlines()):\n if index == 0 and row.startswith(BOM_UTF8):\n row = row[len(BOM_UTF8):]\n cells = [ self._process(c...
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. class _Setting(object): def __init__(self, setting_name, parent=None, comment=None): self.setting_name = setting_name self.parent = parent self.comment = comment self.reset() def reset(self): self.value = [] @property def source(self): return self.parent.source if self.parent else None @property def directory(self): return self.parent.directory if self.parent else None def populate(self, value, comment=None): """Mainly used at parsing time, later attributes can be set directly.""" self._populate(value) self.comment = comment def _populate(self, value): self.value = value def is_set(self): return bool(self.value) def is_for_loop(self): return False def report_invalid_syntax(self, message, level='ERROR'): self.parent.report_invalid_syntax(message, level) def _string_value(self, value): return value if isinstance(value, basestring) else ' '.join(value) def _concat_string_with_value(self, string, value): if string: return string + ' ' + self._string_value(value) return self._string_value(value) def as_list(self): ret = self._data_as_list() if self.comment: ret.append('# %s' % self.comment) return ret def _data_as_list(self): ret = [self.setting_name] if self.value: ret.extend(self.value) return ret class Documentation(_Setting): def reset(self): self.value = '' def _populate(self, value): self.value = self._concat_string_with_value(self.value, value) def _data_as_list(self): return [self.setting_name, self.value] class Template(_Setting): def reset(self): self.value = None def _populate(self, value): self.value = self._concat_string_with_value(self.value, value) def is_set(self): return self.value is not None def _data_as_list(self): ret = [self.setting_name] if self.value: ret.append(self.value) return ret class Fixture(_Setting): def reset(self): self.name = None self.args = [] def _populate(self, value): if not self.name: self.name = value[0] if value else '' value = value[1:] self.args.extend(value) def is_set(self): return self.name is not None def _data_as_list(self): ret = [self.setting_name] if self.name or self.args: ret.append(self.name or '') if self.args: ret.extend(self.args) return ret class Timeout(_Setting): def reset(self): self.value = None self.message = '' def _populate(self, value): if not self.value: self.value = value[0] if value else '' value = value[1:] self.message = self._concat_string_with_value(self.message, value) def is_set(self): return self.value is not None def _data_as_list(self): ret = [self.setting_name] if self.value or self.message: ret.append(self.value or '') if self.message: ret.append(self.message) return ret class Tags(_Setting): def reset(self): self.value = None def _populate(self, value): self.value = (self.value or []) + value def is_set(self): return self.value is not None def __add__(self, other): if not isinstance(other, Tags): raise TypeError('Tags can only be added with tags') tags = Tags('Tags') tags.value = (self.value or []) + (other.value or []) return tags class Arguments(_Setting): pass class Return(_Setting): pass class Metadata(_Setting): def __init__(self, setting_name, parent, name, value, comment=None): self.setting_name = setting_name self.parent = parent self.name = name self.value = self._string_value(value) self.comment = comment def is_set(self): return True def _data_as_list(self): return [self.setting_name, self.name, self.value] class _Import(_Setting): def __init__(self, parent, name, args=None, alias=None, comment=None): self.parent = parent self.name = name self.args = args or [] self.alias = alias self.comment = comment @property def type(self): return type(self).__name__ def is_set(self): return True def _data_as_list(self): return [self.type, self.name] + self.args class Library(_Import): def __init__(self, parent, name, args=None, alias=None, comment=None): if args and not alias: args, alias = self._split_alias(args) _Import.__init__(self, parent, name, args, alias, comment) def _split_alias(self, args): if len(args) >= 2 and args[-2].upper() == 'WITH NAME': return args[:-2], args[-1] return args, None def _data_as_list(self): alias = ['WITH NAME', self.alias] if self.alias else [] return ['Library', self.name] + self.args + alias class Resource(_Import): def __init__(self, parent, name, invalid_args=None, comment=None): if invalid_args: name += ' ' + ' '.join(invalid_args) _Import.__init__(self, parent, name, comment=comment) class Variables(_Import): def __init__(self, parent, name, args=None, comment=None): _Import.__init__(self, parent, name, args, comment=comment)
[ [ 3, 0, 0.1777, 0.2273, 0, 0.66, 0, 307, 0, 13, 0, 0, 186, 0, 11 ], [ 2, 1, 0.0826, 0.0207, 1, 0.81, 0, 555, 0, 4, 0, 0, 0, 0, 1 ], [ 14, 2, 0.0785, 0.0041, 2, 0.01...
[ "class _Setting(object):\n\n def __init__(self, setting_name, parent=None, comment=None):\n self.setting_name = setting_name\n self.parent = parent\n self.comment = comment\n self.reset()", " def __init__(self, setting_name, parent=None, comment=None):\n self.setting_name ...