How to use OR operator in RF? - robotframework

My testcase needed to set two or more value in order to evaluate with ${value} but this syntax does not work!
I appreciate if anybody could guide me.
${status} = Evaluate ${value} != 11 || 5

When you use Evaluate the expression must be valid Python.
In your case you could use:
${status} = Evaluate ${value} != 11 or ${value} != 5
or
${status} = Evaluate ${value} not in [11, 5]

Related

Making an option with optparse

I am looking to create a couple of options with optparse in R. I want to feed the R script an argument from bash. This option will first check the length of the argument and then it will check if the argument contains all numbers or a combo of numbers and letters. This should be written as an if then statement.
So what I have so far:
if (opt$TYPE) != "RUNDATE" && str_length(opt$IDNO) != 8 && opt$IDNO != opt$IDNO[0-9]{8} {
print_help(opt_parser)
stop("Not a valid Identity Number.n", call. = FALSE)
}
if (opt$TYPE) != "LIMSID" && str_length(opt$IDNO) == 7 && opt$IDNO != opt$IDNO[A-Z]{3}[0-9]{4} {
print_help(opt_parser)
stop("Not a valid Identity Number.n", call. = FALSE)
}
Example: ABC1234 & ABCD123
needs to be checked so that the first three characters are letters, and that the last four characters are numbers. This would allow ABC1234 to proceed while ABCD123 would trigger the error message and stop the function.
I have an idea for the syntax in bash and am looking for it's equivalent in R:
[[A-Z]]{3}[0-9]{4}

Luhn algorithm Robot Framework

I am new to robot framework and trying to implement Luhn Algorithm.
I found the code in python and want to change it to Robot framework.
def cardLuhnChecksumIsValid(card_number):
""" checks to make sure that the card passes a luhn mod-10 checksum """
sum = 0
num_digits = len(card_number)
oddeven = num_digits & 1
for count in range(0, num_digits):
digit = int(card_number[count])
if not (( count & 1 ) ^ oddeven ):
digit = digit * 2
if digit > 9:
digit = digit - 9
sum = sum + digit
return ( (sum % 10) == 0 )
I started with robotscript and was stuck at statement if not (( count & 1 ) ^ oddeven ) can someone please help me convert the above code to robot script
is there a automated to change python code to robot ?
cardLuhnChecksumIsValid
[Arguments] ${ICCID1}
${num_digits} Get length ${ICCID1}
${odd_even} ${num_digits}
... AND ${1}
FOR ${Count} IN RANGE 0 ${num_digits}
${digit} Convert To Integer ${ICCID[${Count}]}
Have a look at on the Evaluate keyword in the BuiltIn library. You can use that to rewrite:
if not (( count & 1 ) ^ oddeven ):
digit = digit * 2
to:
${condition}= Evaluate not (( ${count} & 1 ) ^ ${oddeven} )
${digit}= Run Keyword If ${condition} Evaluate ${digit} * 2
You can rewrite the rest of the algorithm using the same approach. From Robot Framework 3.2 release you can also use Inline Python evaluation.
*** Test Cases ***
Check - ICCID
[Setup] setup
${ICCID} Card.get ICCID #get ICCID
${Result_Chksum} cardLuhnChecksumIsValid ${ICCID}
[Teardown] tearDown
*** Keywords ***
setup
No Operation
tearDown
No Operation
cardLuhnChecksumIsValid
[Arguments] ${ICCID_val}
${num_digits} Get length ${ICCID_val}
${oddeven}= Evaluate ( ${1} & ${num_digits} )
FOR ${Count} IN RANGE 0 ${num_digits}
${digit} Convert To Integer ${ICCID_val[${Count}]}
${condition}= Evaluate not (( ${Count} & 1 ) ^ ${oddeven} )
${digit}= Run Keyword If ${condition} Evaluate (${digit}*2)
... ELSE Set Variable ${digit}
${digit}= Run Keyword If (${digit} > 9) Evaluate (${digit} - 9)
... ELSE Set Variable ${digit}
${Sum}= Evaluate (${Sum}+${digit})
END
${result}= Evaluate (${Sum}%10)
[Return] ${result}

R: Parsing boolean command line argument in using argparse

I am using "argparse" library in R for command line arguments.
# Create parser
parser = ArgumentParser(description='command line args')
# Add command line arguments
parser$add_argument("is_local", nargs='?', type="logical",
help="whether to use local or server path", default=FALSE)
parser$add_argument("alert", nargs='?', type="double",
help="alert threshold", default=0.99)
I am trying to call it on command line such as:
Rscript my_func.R TRUE 0.99
However boolean argument does not change. Any idea how to parse boolean argument in R?
Thanks!
I don't know R, but the description of this package says it's a wrapper for the Python argparse.
I would recommend changing these:
parser$add_argument("is_local", nargs='?', type="logical",
help="whether to use local or server path", default=FALSE)
parser$add_argument("alert", nargs='?', type="double",
help="alert threshold", default=0.99)
to
parser$add_argument("--local", action='store_true'),
help="whether to use local or server path")
parser$add_argument("--alert", type="double",
help="alert threshold", default=0.99)
which would be called with
Rscript my_func.R --local --alert 0.99
store_true is illustrated on the basic docs page, https://github.com/trevorld/r-argparse
If I read the R correctly, your is_local should be giving you a warning
"You almost certainly want to use action='store_true' or action='store_false' instead"
A store_true argument sets the attribute to TRUE if present, and the default FALSE if absent. It should be an optional (--) and not set the nargs.
(It is possible to have an argument that takes strings 'true' and 'false' (or any other pair in your native language) and converts them to logical values, but requires more coding.)
I made --alert a flagged argument as well, without the nargs. Its value will be the default if absent, and the convert the string to a double if provided. It could be a '?' positional, but while learning I think it's best to stick with optionals unless you want the argument to be required.
The R-argparse docs aren't very complete. You may need to refer to the Python docs, and experiment to get the translation right.
https://docs.python.org/3/library/argparse.html
Thanks for your time and help!
I would like to share my workaround for the problem as I find original argparse (action) usage a bit complicated.
# Convert str input to boolean
str2bool = function(input_str)
{
if(input_str == "0")
{
input_str = FALSE
}
else if(input_str == "1")
{
input_str = TRUE
}
return(input_str)
}
# Create parser
parser = ArgumentParser(description='command line args')
# Add command line arguments
parser$add_argument("is_local", nargs='?', type="character",
help="whether to use local or server path", default="1")
parser$add_argument("alert", nargs='?', type="double",
help="alert threshold", default=0.99)
# Parse arguments
args = parser$parse_args()
# Convert str arguments
args$is_local = str2bool(args$is_local)
# Call on CMD line
Rscript my_func.R 1 0.99 #equivalent Rscript my_func.R TRUE 0.99
Rscript my_func.R 0 0.99 #equivalent Rscript my_func.R FALSE 0.99
Below is the sample example given in the official docs of package argparse:
parser <- ArgumentParser(description='Process some integers')
parser$add_argument('integers', metavar='N', type="integer", nargs='+',
help='an integer for the accumulator')
parser$add_argument('--sum', dest='accumulate', action='store_const',
const='sum', default='max',
help='sum the integers (default: find the max)')
parser$print_help()
# default args for ArgumentParser()$parse_args are commandArgs(TRUE)
# which is what you'd want for an Rscript but not for interactive use
args <- parser$parse_args(c("--sum", "1", "2", "3"))
accumulate_fn <- get(args$accumulate)
print(accumulate_fn(args$integers))
Here is the link for the argparse pdf https://cran.r-project.org/web/packages/argparse/argparse.pdf
I hope it might help.

Check if palindrome while ignoring special characters

I'm failing the last test case, which is the one with the spaces and single quotation mark.
I used s.strip, but the error still persists.
Is there another way to go about this?
Thank you.
from test import testEqual
def removeWhite(s):
s.strip()
s.strip("'")
return s
def isPal(s):
if s == "" or len(s) == 1:
return True
if removeWhite(s[0]) != removeWhite(s[-1]):
return False
return isPal(removeWhite(s[1:-1]))
testEqual(isPal(removeWhite("x")),True)
testEqual(isPal(removeWhite("radar")),True)
testEqual(isPal(removeWhite("hello")),False)
testEqual(isPal(removeWhite("")),True)
testEqual(isPal(removeWhite("hannah")),True)
testEqual(isPal(removeWhite("madam i'm adam")),True)
At first your removeWhite function doesn't return all spaces because strip only removes from the end and the beginning of a string. See:
>>> " a ".strip()
'a'
>>> " a a ".strip()
'a a'
So i suggest this approach:
def removeWhite(s):
return ''.join(filter(lambda x: x not in " '", s))
Please note that I use join because filter returns an iterator which needs to be converted back to a string.
For finding the palindromes i would suggest this function:
def isPal(s):
if len(s) <= 1: # Special case to prevent KeyError later
return True
stripped = removeWhite(s) # Strip off all whitespaces
first = stripped[:len(stripped) // 2] # First half of the string
if len(stripped) % 2: # Length of string is even?
second = stripped[len(stripped) // 2 + 1:] # Drop the middle character
else:
second = stripped[len(stripped) // 2:] # Else keep it
secondrev = ''.join(reversed(second)) # Reverse the second half
return first == secondrev # And return wether they're equal.
This holds for all your examples. But it think your isPal function should work too if you fix your removeWhite function

How to check if arguments have been correctly passed to Rscript on Windows

I'm trying to write an R script that takes in 3 arguments when run with Rscript: input file name, whether it has a header or not (values are 'header' or 'no_header', and a positive integer (the number of replacements; its for a bootstrap application). So, when I run it this way:
Rscript bootstrapWithReplacement.R survival.csv header 50
it should, before running, check if:
1) The script indeed took in 3 parameters;
2) whether the first parameter is a file;
3) whether the second parameter has a 'header' or 'no_header' value, and
4) if the number passed is a positive integer.
Here is my code so far:
pcArgs <- commandArgs()
snOffset <- grep('--args', pcArgs)
inputFile <- pcArgs[snOffset+1]
headerSpec <- pcArgs[snOffset+2] ## header/no_header
numberOfResamples <- pcArgs[snOffset+3] ## positive integer
check.integer <- function(N){
!length(grep("[^[:digit:]]", as.character(N)))
}
if (!file_test("-f",inputFile)) {stop("inputFile not defined. Proper use: Rscript bootstrapWithReplacementFile.R survival.csv header 50.")}
if (!exists("headerSpec")) {stop("headerSpec not defined. Proper use: Rscript bootstrapWithReplacementFile.R survival.csv header 50.")}
if (!exists("numberOfResamples")) {stop("numberOfResamples not defined. Proper use: Rscript bootstrapWithReplacementFile.R survival.csv header 50.")}
if ((headerSpec != 'header') == TRUE & (headerSpec != 'no_header') == TRUE) {stop("headerSpec not properly defined. Correct values: 'header' OR 'no_header'.")}
if (check.integer(numberOfResamples) != TRUE | (numberOfResamples>0) != TRUE) {stop("numberOfResamples not properly defined. Must be an integer larger than 0.")}
if (headerSpec == 'header') {
inputData<-read.csv(inputFile)
for (i in 1:numberOfResamples) {write.csv(inputData[sample(nrow(inputData),replace=TRUE),], paste("./bootstrap_",i,"_",inputFile,sep=""), row.names=FALSE)}
}
if (headerSpec == 'no_header') {
inputData<-read.table(inputFile,header=FALSE)
for (i in 1:numberOfResamples) {write.table(inputData[sample(nrow(inputData),replace=TRUE),], paste("./bootstrap_",i,"_",inputFile,sep=""),
sep=",", row.names=FALSE, col.names=FALSE)}
}
My problem is, the check for the existence of a file works, but for the header or integer don't.
Also, how can I, in the beginning, check if all three arguments have been passed?
Thanks!
As Vincent said, you should use the trailingOnly argument to commandArgs to simplify things.
As Konrad said, never, ever, ever compare directly to TRUE and FALSE.
Also, use assertive for doing assertions.
library(assertive)
library(methods)
cmd_args <- commandArgs(TRUE)
if(length(cmd_args) < 3)
{
stop("Not enough arguments. Please supply 3 arguments.")
}
inputFile <- cmd_args[1]
if (!file_test("-f", inputFile))
{
stop("inputFile not defined, or not correctly named."
}
headerSpec <- match.arg(cmd_args[2], c("header", "no_header"))
numberOfResamples <- as.numeric(cmd_args[3])
assert_all_numbers_are_whole_numbers(numberOfResamples)
assert_all_are_positive(numberOfResamples)
message("Success!")
I managed to solve all the checks, here's how:
if ((length(pcArgs) == 8) == FALSE) {stop("Not enough arguments. Please supply 3 arguments. Proper use example: Rscript bootstrapWithReplacementFile.R survival.csv header 50.")}
if (!file_test("-f",inputFile)) {stop("inputFile not defined, or not correctly named. Proper use example: Rscript bootstrapWithReplacementFile.R survival.csv header 50.")}
if ((headerSpec != 'header') == TRUE & (headerSpec != 'no_header') == TRUE) {stop("headerSpec not properly defined. Correct values: 'header' OR 'no_header'.")}
if (check.integer(numberOfResamples) != TRUE | (numberOfResamples>0) != TRUE) {stop("numberOfResamples not properly defined. Must be an integer larger than 0.")}
Thanks everyone!

Resources