Ruby transform string to method name - ruby

To test image urls in a ruby project I can call a function as follows
validate_url("some_valid_url", "valid")
validate_url("inv#alid-url", "invalid")
The function looks like this:
def validate_url(image_url, state)
assert state === 'valid' ? new_product(image_url).valid? : new_product(image_url).invalid?,
"#{image_url} should always be " + state.upcase
end
is there a way to rewrite the line:
assert state === 'valid' ? new_product(image_url).valid? : new_product(image_url).invalid?
to something like
assert new_product(image_url).state.What-To-Do-Here?
which would then be equals to the following if state contains the string "valid"
assert new_product(image_url).valid?

You can do....
assert new_product(image_url).send(state + '?'), "#{image_url} should always be #{state.upcase}"
It would be prudent to ensure that state can only contain "valid" or "invalid"

Related

I get this error: 'list' object has no attribute 'countPoints'

When I import this code that I typed in here in to another code I get the error: 'list' object has no attribute 'countPoints' .
import ModuleRollDice as dce
def judge(rollPlayerA,rollPlayerB):
if not all(item in dce.options for item in rollPlayerA) or
not all(item in dce.options for item in rollPlayerB):
print("error")
if rollPlayerA.countPoints(rollPlayerA[0]) == len(rollPlayerA) and
rollPlayerB.countPoints(rollPlayerB[0]) != len(rollPlayerB):
return "A"
if rollPlayerA.countPoints(rollPlayerA[0]) != len(rollPlayerA) and
rollPlayerB.countPoints(rollPlayerB[0]) == len(rollPlayerB):
return "B"
elif sum(rollPlayerA) == sum(rollPlayerB):
return "tie"
elif sum(rollPlayerA) > sum(rollPlayerB):
return "A"
else:
return "B"
return
It appears as though the arguments passed to rollPlayerA/B are not list types objects. You should sanity check this beforehand to ensure that what is recieved is in fact a list type object. The issue can be resolved by both sanity checking and looking at the caller function and seeing what is being sent as arguments.
A simple sanity check could look like:
def judge(rollPlayerA,rollPlayerB):
if type(rollPlayerA) is not type(list) or
type(rollPlayerB) is not type(list):
print("judge function did not recieve proper input types")
return
...
Another way of doing this would be using pythons assert
def judge(rollPlayerA,rollPlayerB):
assert(type(rollPlayerA) == type(list)), "rollPlayerA is not a list"
assert(type(rollPlayerB) == type(list)), "rollPlayerB is not a list"
An even nicer way of doing this would be using PEP 3107's implementation of type assertions in definition declarations:
def judge(rollPlayerA: list, rollplayerB: list) -> None:
....
This also allows you to remove the redundant 'return' statement at the end of your function, which you didn't really need anyways

How do I evaluate a string key in Groovy so that it outputs a value?

we're defining a key/value property in ~/.gradle/gradle.properties like so:
~/.gradle/gradle.properties:
FOO=BAR
If we do:
println "$FOO" // prints BAR
it works, but if we try to make it a function that looks like this:
def getEnvValueForKey = { keyStr ->
return "$keyStr"
}
getEnvValueForKey("FOO") returns FOO instead of BAR
How do we make that work?
Your getEnvValueForKey(key) function returns always a GString representation of a variable passed as a parameter. The expression "$keyStr" is actually an alternative for "" + keyStr.toString(). The same thing happens when you call "$FOO" == "" + FOO.toString().
If you want to get a property defined in gradle.properties file you can redefine your function to something like this:
def getEnvValueForKey = { keyStr ->
return this.getProperties().getOrDefault(keyStr, null)
}
Calling getEnvValueForKey("FOO") in this case evaluates to
this.getProperties().getOrDefault("FOO", null)
If in current scope variable FOO exists it will return its value and null otherwise.
Keep in mind that this.getProperties() returns a map of all properties/variables defined in current scope of Gradle task being executed.

extract value for calculated attribute

within Rails4, the following logic determines an attribute
if #items.count == 1
value = "disc1"
elsif #items.count == 2
value = "disc2"
else
end
which would then need to be accessed
#cluster.value
however this syntax does not work as the value is not a method. How can this variable be employed to extract the object's thus-named attribute?
It would be better if you just conditionally call methods:
if #items.count == 1
#cluster.disc1
elsif #items.count == 2
#cluster.disc2
else
# ...
end
Still, if you want to go that route:
#cluster.public_send value
Or if #cluster is an ActiveRecord model and you want to fetch the stored value in the corresponding table, you could:
#cluster[value]

SoapUI: How to cast 0 as 'false'

I'm using SoapUI to test a WCF service. I have an XPath Match assertion in which the Declare is:
if (boolean(//a:IsClick/text()[1])) then //a:IsClick else ''
For the source XML, the node is
<a:IsClick>false</a:IsClick>
so the Declare section equates to 'false'.
The Expected box has this:
${#ResponseAsXml#(//CLICK[text()],'')}
and the XML (from a JDBC Test Step) is:
<CLICK>0</CLICK>
so the expected value is 0.
I need to have these two equate so my assertion will pass. One way to do this would be to cast the Expected result from 0 to 'false'. How can I do that? Or is there a better approach?
In XPath the boolean() function returns a boolean for number, string, or node-set. In your case where you want to cast a number to a boolean, boolean(0) returns false, for the rest of numbers boolean(n) returns true. In the other hand boolean() of string returns false for boolean('false') or for boolean('') (empty string) for the rest of strings boolean() returns true. So your problem is that using text() you're getting the '0' as string instead of a number so when you try to cast boolean('0') you're getting true.
In your case if you've some XML result from your JDBC Test Step like:
<Results>
<CLICK>0</CLICK>
</Results>
You can convert this 0 to false adding boolean() to your expression and also using number() function instead of text(). So to cast the 0 to false use:
${#ResponseAsXml#(boolean(//CLICK[number()]))}
instead of:
${#ResponseAsXml#(//CLICK[text()],'')}
Hope this helps,
The simplest solution is to turn this into a Groovy problem - a Groovy assertion.
Here is a visualization (see documentation):
def negIsClick = "false"
def negCLICK = "0"
def posIsClick = "true"
def posCLICK = "1"
// fake "cast" the text to boolean
assert !(negIsClick.equals("true") ?: false)
assert (posIsClick.equals("true") ?: false)
assert !negCLICK.toInteger() // zero is false
assert posCLICK.toInteger() // all other numbers are true
// note the exclamations everywhere
assert !(negIsClick.equals("true") ?: false) == !negCLICK.toInteger()
assert !(posIsClick.equals("true") ?: false) == !posCLICK.toInteger()
// this fails
assert (negIsClick.equals("true") ?: false) == negCLICK.toInteger()
The last one fails, because you cannot compare a boolean to an integer. But in the cases before that, the ! first casts everything to booleans.
So in your case, you will need to do something like:
// read in the two values
def IsClick = context.expand( '${XML test step#Response//*:IsClick}' )
def CLICK = context.expand( '${JDBC test step#ResponseAsXml//*:CLICK}' )
// now compare them
assert !(IsClick.equals("true") ?: false) == !CLICK.toInteger()
assert '1'.toInteger().asBoolean()
assert !'0'.toInteger().asBoolean()

QTP handling Null values with public functions

I am trying to write a QTP Script which works as follows
* takes a column from table checks if it is null
if yes
it adds that column name in a variable .
Later that column name will be used to display to user that all such fields are left blank .
Something like this:
Set rsRecordset1 = dbConnection.Execute("select formcd,sndrpstlcd,recppstlcd,sndrcntrycd, from test_data where trk in ('"&tin&"')")
If rsRecordset1.EOF = false Then
Blank_field="blank_fields->"
formcd = rsRecordset1("formcd").value
typcd="formcd"
Call validatenull (typcd,Blank_field)
packaging = rsRecordset1("packaging").value
typcd="packaging"
Call validatenull (typcd,Blank_field)
......
Public function validatenull (typcd,Blank_field)
If (isnull(typcd) )Then
Blank_field = Blank_field & " " & typcd &", "
End If
End Function
Value of blank_Field is expected to catch values as "blank_fields->Form_id,packaging (Considering Form_id, Packaging passes Null values) {It shouldnt add values which are not Null to blank_fields}
In simpler words
ss = Null
call nnn(ss)
Public function nnn(ss)
If isnull(ss) Then
msgbox("yes")
End If
End Function
Has Error that msgbox does not populates But,
ss= Null
nnn(ss)
If isnull(ss) Then
msgbox("yes")
End If
Populates Msgbox as Yes
But I want Case 1 to be working and I do not want to add any more variables to the function name.
IF By making an Array we can do it, please suggest .
It appears your function works fine, but you are passing the wrong values. From your code snippet:
formcd = rsRecordset1("formcd").value
typcd="formcd"
Call validatenull (typcd,Blank_field)
When you call 'validatenull', you are passing the variable 'typecd'. On the previous line, you populate this variable with a string, so it will never be null. It appears what you intended to pass was the variable 'formcd'. Your second call to 'validatenull' does the same thing. Here is your first call modified to use the other variable.
formcd = rsRecordset1("formcd").value
typcd="formcd"
Call validatenull (formcd,Blank_field)

Resources