Python Robot Framework : How to convert robot's txt code into Python code - robotframework

Please tell me how to convert following robot (txt) code into Python code. Robot code.
*** Settings ***
Library OperatingSystem
*** Keywords ***
nik_key_1
[Arguments] ${arg1_str}
log to console ${arg1_str}
*** Variables ***
${var1} "variable1"
*** Test Cases ***
First Test Case
${output}= run "hostname"
log to console ${output}
${str1}= catenate "nikhil" "gupta"
nik_key_1 "NikArg1"
log to console ${var1}
log to console ${str1}
Following is the code that I tried :
from robot.api import TestSuite
from robot.running.model import Keyword
from robot.libraries.BuiltIn import BuiltIn
from robot.api.deco import keyword
bi = BuiltIn()
#keyword(name='nik_key_1')
def nik_key_1(username):
bi.log_to_console(message=username,stream='STDOUT',no_newline=False)
suite = TestSuite('Activate Skynet')
suite.resource.imports.library("OperatingSystem")
keyword1 = Keyword(name="nik_key_1",type='kw',doc="nik_key_doc1",args=
["nikusername"])
suite.keywords.append(keyword1)
test = suite.tests.create(name='nik_test_case1', tags=['smoke'])
test.doc = "nik doc"
print dir(test.keywords)
test.keywords.create('nik_key_1', args=['nikusername'],type='kw')
result = suite.run(critical='smoke', output='skynet.xml')
Following is the error I am getting :
No keyword with name 'nik_key_1' found.

Your code doesn't work because robot doesn't look at your script for context, and thus doesn't know about the nik_key_1. Since your suite doesn't import this script, it can't access any functions. You'll need to move nik_key_1 to a file, and import that file in the suite.
For example, create a file named keywords.py, and put this in it:
# keywords.py
from robot.api.deco import keyword
from robot.libraries.BuiltIn import BuiltIn
bi = BuiltIn()
#keyword(name='nik_key_1')
def nik_key_1(username):
bi.log_to_console(message=username,stream='STDOUT',no_newline=False)
Next, modify your test to include this library:
suite.resource.imports.library('keywords.py')
You can then call the keyword from your test.
Using your script as a library
It's possible to combine your script and the keywords in a single file, but that involves making your script importable by protecting the executable code from running when the file is imported.
For example, you can rewrite your script to be like the following. Notice how the executable portion of the script is inside a block that tests whether the file is imported or not. Also notice that the script itself is added as a library (suite.resource.imports.library(__file__))
from robot.api import TestSuite
from robot.running.model import Keyword
from robot.libraries.BuiltIn import BuiltIn
from robot.api.deco import keyword
bi = BuiltIn()
#keyword(name='nik_key_1')
def nik_key_1(username):
bi.log_to_console(message=username,stream='STDOUT',no_newline=False)
if __name__ == "__main__":
suite = TestSuite('Activate Skynet')
suite.resource.imports.library('OperatingSystem')
suite.resource.imports.library(__file__)
test = suite.tests.create('Should Activate Skynet', tags=['smoke'])
test.keywords.create('Set Environment Variable', args=['SKYNET', 'activated'], type='setup')
test.keywords.create('Environment Variable Should Be Set', args=['SKYNET'])
test.keywords.create('nik_key_1', args=['nikusername'],type='kw')
result = suite.run(critical='smoke', output='skynet.xml')

Related

Not able to call selenium keyword written in python in RobotFramework

I have created one directory(ExternalKeyword) and inside directory created one CommonKeywords.py file, inside .py file written code below
from robot.libraries.BuiltIn import BuiltIn
from robot.libraries.DateTime import datetime
from SeleniumLibrary import SeleniumLibrary
from selenium.webdriver.remote.webelement import WebElement
from selenium.webdriver.remote.command import Command
class BasePage():
def __init__(self):
self.session = SeleniumLibrary(run_on_failure='Nothing')
self.builtin = BuiltIn()
self.datetime = datetime
self.set_browser_settings()
def screenshot(self):
self.session.capture_page_screenshot()
def set_browser_settings(self, browser='gc', timeout=10, implicit_wait=10, speed=0.1, run_on_failure='screenshot',
screenshot_root_directory=None):
self.browser = browser
self.selenium_timeout = timeout
self.implicit_wait = implicit_wait
self.selenium_speed = speed
self.run_on_failure = run_on_failure
def input_text1(self, locator, text):
for i in range(3):
try:
self.session.wait_until_element_is_visible(locator)
self.session.input_text(locator, text)
break
except:
if i in range(2):
self.builtin.sleep(2)
else:
self.screenshot()
raise
Now I am trying to call input_text1 keyword in .robot file. But I can't able to call getting below error. Undefined keyword
Below is the code were calling input_text1 from .py file.
*** Settings ***
Library SeleniumLibrary
Library ../ExternalKeywords/UserDefinedKeywords.py
Library ../ExternalKeywords/CommonKeywords.py
*** Keywords ***
Lounch Browser
[Arguments] ${url} ${Browser}
Open Browser ${url} ${Browser}
Maximize Browser Window
Login into application
[Arguments] ${UserName} ${Password}
input_text1 id=UserName ${UserName}
input_text id=Password ${Password}
get_text id=loginButton
Click Button id=loginButton
Can someone help me to resolve my issue. why I am not able to call python keyword in .robot file.
The simplest way to write a keyword that works with the selenium library is to use the get library instance keyword to get a reference to the instance of SeleniumLibrary, instead of directly instantiating the class.
Example:
from robot.libraries.BuiltIn import BuiltIn
class BasePage():
def __init__(self):
self.session = BuiltIn().get_library_instance("SeleniumLibrary")
When you do it like that, and assuming your test has imported the library and opened a browser, you are able to call the SeleniumLibrary keywords via self.session like you do elsewhere in your code:
def screenshot(self):
self.session.capture_page_screenshot()

There is no keyword to check a if a non regular exist on robot framework

Current implementation of keyword File Should Exist is using os.path.isfile() that returns false if is not a regular file. Is there a keyword to check non regular, as block or character device files?
I'm not aware of such a keyword. But if you can do it in Python, you can do it in RF.
Example Python function you can turn into RF keywords:
Libraries/file-utils.py
import os, stat
from robot.utils.asserts import assert_true
def block_file_should_exist(file):
assert_true(stat.S_ISBLK(os.stat(file).st_mode))
def character_file_should_exist(file):
assert_true(stat.S_ISCHR(os.stat(file).st_mode))
and an example test:
*** Settings ***
Library ../Libraries/file-utils.py
*** Test Cases ***
Character File Exists
Character File Should Exist /dev/zero

When tried to access keyword from Custom Library, error InvalidArgumentException is displayed

When tried to access keyword from Custom Library, error InvalidArgumentException is displayed
I am using below folder structure to maintain my test scripts
Test_Scripts
TestCase
TestSuite1.robot
SupportFiles
RF_CustomLibrary.py
TestSuite1.robot
*** Settings ***
Library SeleniumLibrary
Library ..\\SupportFiles\\RF_CustomLibrary.py
*** Variables ***
${Browser} Chrome
*** Test cases ***
Sample Test Case
Verify Paste text functionality
*** Keywords ***
Verify Paste text functionality
Set Library Search Order RF_CustomLibrary
Open Browser https://gmail.com ${BROWSER}
Sleep 2s
Maximize Browser Window
Wait Until Keyword Succeeds 60s 2s Element Should Be Visible ${L_Login_btn}
PasteTextFunction id=identifierId Username1
Custom library: RF_CustomLibrary.py
import os
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from SeleniumLibrary import SeleniumLibrary
from SeleniumLibrary.base import LibraryComponent, keyword
from SeleniumLibrary.errors import ElementNotFound
from SeleniumLibrary.utils import is_noney
class RF_CustomLibrary(SeleniumLibrary):
#keyword
def pasteTextFunction(self, locator, text):
os.system("echo off | clip")
os.system("echo %s| clip" % text.strip())
element = self._current_browser().find_element(locator)
element.clear()
element.send_keys(Keys.CONTROL, 'v')
When i execute this test case, below error message is displayed for the keyword "PasteTextFunction"
InvalidArgumentException: Message: invalid argument: invalid locator
Any suggestions/inputs to sort out this error would be helpful.
You are calling the low-level selenium function find_element, but passing in a SeleniumLibrary-style locator (id=identifierId) which is not something that the low level selenium driver understands.
If you want to use a SeleniumLibrary locator, you need to use the Get webelement method of SeleniumLibrary instead.
element = self.get_webelement(locator)

nose.run returns blank file when used with xunit arguments

I am using nose to run my tests the following way
import nose
import unittest
if __name__ == "__main__":
test_cases = unittest.TestLoader().discover(<path_to_test_files>)
suite = unittest.TestSuite([test_cases])
xunit_report = True
log_file = 'my_report.xml'
arguments = ["nosetest",'--verbosity=2']
if xunit_report:
arguments += ['--with-xunit', '--xunit-file', log_file]
nose.run(suite=suite, argv=arguments)
The suite variable is updated with all the test cases discovered. The console log also validates that all the tests got executed.
However, the xml result file always contains
<?xml version="1.0" encoding="UTF-8"?><testsuite name="nosetests" tests="0" errors="0" failures="0" skip="0"></testsuite>
Am on Python 2.7.14.
What do I need to change to get the actual results in my xml file?
If you change the discover() call to a provide a path, like . for the current directory:
test_cases = unittest.TestLoader().discover('.')
Then the loader will find files in the working directory that you are executing the script from that match the pattern 'test*.py'. If I add add your script to a file run.py, and a test next to it in a file named test_example.py, with the following UnitTest test:
import unittest
class TestStringMethods(unittest.TestCase):
def test_upper(self):
self.assertEqual('foo'.upper(), 'FOO')
Then the output xml file contains the expected test results.
So: Make sure you're running the script from the same directory your tests are in (or that you change .discover('.') to whatever directory your tests are in, and that your test files match the test*.py pattern.
Also note that that nose.run(..) has an argument for just a module name to find tests in that you may find useful:
nose.run(module=".")

Robot framework split string and put in to sheet excel

I want to split Transaction ID:211444 , i want to get only value = '211444' and put it into sheet excel ?
anyone please help
Use OperatingSystem.py and String.py libraries:
${string} = Convert to String Transaction ID:211444
${id} = Fetch From Right ${string} ID:
append to file ids.csv ID:${id}\n encoding=UTF-8
This might be useful to you .
may sure you have xlsxwriter installed in your python packages .
else do
pip install xlsxwriter
Below is robotfile content which will pass the alphanumeric string to a library written in python
sample.robot
*** Settings ***
#test.py is name of python file in which code to write in excel is written
Library test.py
*** Variables ***
#This is sample alphanumeric value passed to python function
${test} pankaj:12232
*** Test Cases ***
Test
value is
*** Keywords ***
value is
#excel_numeric is function written in python to remove strings and write to excel
excel_numeric ${test}
#log to console ${compare}
Python file
test.py
import xlsxwriter
def excel_numeric(arg1):
import re
#this will only provide numeric value from strings
arg2=re.findall(r'\d+',arg1)
workbook = xlsxwriter.Workbook(r'D:\dummy.xlsx')
worksheet = workbook.add_worksheet()
for item in arg2:
print item
#write takes three arguments,row,column and value
worksheet.write(0,0,item)
workbook.close()
output :
12232 - Written in excelfile
Note
Make sure you put robot and python file in same directory

Resources