How to get only value of sql query without header using groovy - groovy

I tried to fetch only DB value using groovy script but result includes the value along with header.
def res = con.rows("select fkuserid from tblUserCardDetail where cardValue='111633072'" )
log.info "The User ID from DB is :" + res
Result is coming like this :
Mon Apr 25 06:51:07 PDT 2016:INFO:The User ID from DB is :[[fkuserid:2951]]
I want only value : 2951

When Groovy SQL returns a result, it returns it as a Map-like object, a GroovyRowResult. Since you're using rows() you're getting a list of GroovyRowResults.
If the query will always return a single record (or nothing at all), then you can use firstRow() instead of rows(). Then, you can access the fkuserid property/key to get the value:
def res = con.firstRow("select fkuserid from tblUserCardDetail where cardValue='111633072'" )
log.info "The User ID from DB is :" + res.fkuserid

Related

try to modify before display put in variable, but error print(record['recommendation']) become temp=record['recommendation']

from neo4j import GraphDatabase, basic_auth
driver = GraphDatabase.driver(
"neo4j://34.201.9.108:7687",
auth=basic_auth("neo4j", "chart-certifications-bottom"))
cypher_query = '''
MATCH (m:Movie {title:$movie})<-[:RATED]-(u:User)-[:RATED]->(rec:Movie)
RETURN distinct rec.title AS recommendation LIMIT 20
'''
with driver.session(database="neo4j") as session:
results = session.read_transaction(
lambda tx: tx.run(cypher_query,
movie="Crimson Tide").data())
for record in results:
print(record['recommendation']) #<----------------------- OK
driver.close()
try to modify before display put in variable, but error
print(record['recommendation']) become temp=record['recommendation']
#app.get("/neo4j")
def graph_db():
driver = GraphDatabase.driver(
"neo4j://34.201.9.108:7687",
auth=basic_auth("neo4j", "chart-certifications-bottom"))
cypher_query = '''
MATCH (n:Person) RETURN n LIMIT 25
'''
with driver.session(database="neo4j") as session:
results = session.read_transaction(
lambda tx: tx.run(cypher_query,
movie="Crimson Tide").data())
data=[]
for record in results:
temp=record['recommendation'] #<-----------------------error
data.append(temp)
result=data
driver.close()
return{"Result ":result}
When you replaced your query to
MATCH (n:Person) RETURN n LIMIT 25
You are returning nodes of 25 Person and the column recommendation does not exists.
temp=record['recommendation']
Make sure that the result set that your query is returning is the same with the column name that you are accessing.

soapui free version assertions request = response

I will pass any memberid or active card for matching to verify activecard(cardno) matches memberid passed.
Request:
<MemberID>${Property Looper#memberid}</MemberID>
<CardNo>${Property Looper#ActiveCard}</CardNo>
Expected result:
<ReturnMessage>Cardno not found</ReturnMessage>
OR
<ReturnMessage>SUCCESS</ReturnMessage>
How to put assertions to check if the member id in request will check matching with response? contains and not contains assertions seems like not working that well for this condition?
and i want the test to be passed even if the matching failed as the ultimate goal is to make sure the error is not from the data (the test pass regardless the return status) but the application. Thanks
Edit:
after running the step
Edit 2:
after running script assertion
custom property added
You can use Script Assertion to achieve the same.
Based on the description, the assertion should be able to handle both below cases :
some case, you may expect card not found
some case, you may expect SUCCESS
Define test case level custom property, say EXPECTED_MESSAGE and provide appropriate expected value depending on the case.
Add below script assertion for the SOAP Request test step.
//Check if the response is received
assert context.response, 'Response is empty or null'
//Parse the response and find the ReturnMessage value
def actualMessage = new XmlSlurper().parseText(context.response).'**'.find{it.name() == 'ReturnMessage'}?.text()
log.info "Return message from response: $actualMessage"
//Read the expected message from custom property
def expectedMessage = context.expand('${#TestCase#EXPECTED_MESSAGE}')
//Verify with actual value
assert actualMessage == expectedMessage
Let us assume the output is like
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<ReturnMessage>SUCCESS</ReturnMessage>
</soap:Body>
</soap:Envelope>
you can use the below script assertion
def groovyUtils = new com.eviware.soapui.support.GroovyUtils(context)
def response = groovyUtils.getXmlHolder("First Step#Response")
String x = response.getNodeValue("//*[local-name()='ReturnMessage']")
if(x.contains("Cardno not found" ) || x.contains("SUCCESS"))
{
log.info "Success"
}
else
{
log.info " Fail"
}
output is
Sat Oct 28 15:22:02 IST 2017:INFO:Success
Rao's approach is also correct. Its just that if you are following that approach you have to have 2 expected result custom properties since you have 2 properties.
You may have to use if condition before assertion as 1 assertion will fail because your results would be either "Cardno not found" or "SUCCESS"
2 Changes you might have to make in the script. replace 'First Step' with the name of your teststep
change the getNodeValue step to reach the actual place

Python-MySQL : removing single quotes around variable values in query while running db.execute(str, vars)

I am running this code
def details(self, dbsettings, payload):
res = None
with UseDatabase(dbsettings) as db:
sql = "select * from %(tablename)s where userid = %(userid)s"
result = db.run_query_vals(sql, payload)
res = result.fetchall()
return res
but get an error
SQLError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''statuser' where userid = '14'' at line 1
The arguments being passed are :
sql = "select * from %(tablename)s where userid = %(userid)s"
payload = {'tablename' : 'statuser', 'userid' : 14}
As far as I understand, the query being passed to MySQL is along the lines of
select * from 'statuser' where userid = '14'
which is where I get the error; the tablename isnt supposed to be enclosed in quotes. How do I have the name included without the quotes/make them backquotes?
(I don't want to hard-code the table name - this is a variable and is initialised according to different parameters during class creation). Any help here?
You can use the .format() from string in python:
def details(self, dbsettings, payload):
res = None
with UseDatabase(dbsettings) as db:
sql = "select * from {tablename} where userid = {userid}"
sql = sql.format(**payload)
# result = db.run_query_vals(sql, payload) # Method to run query
res = result.fetchall()
return res
I encountered the same problem in pymysql and have figured out a solution:
rewrite the escape method in class 'pymysql.connections.Connection', which obviously adds "'" arround your string.
don't know whether it will help in your case, just sharing a possible way
similiar question: How to remove extra quotes in pymysql
Here's my code:
from pymysql.connections import Connection, converters
class MyConnect(Connection):
def escape(self, obj, mapping=None):
"""Escape whatever value you pass to it.
Non-standard, for internal use; do not use this in your applications.
"""
if isinstance(obj, str):
return self.escape_string(obj) # by default, it is :return "'" + self.escape_string(obj) + "'"
if isinstance(obj, (bytes, bytearray)):
ret = self._quote_bytes(obj)
if self._binary_prefix:
ret = "_binary" + ret
return ret
return converters.escape_item(obj, self.charset, mapping=mapping)
config = {'host':'', 'user':'', ...}
conn = MyConnect(**config)
cur = conn.cursor()

Using Groovy to Loop and Execute Test Steps

I'm trying to do dynamic testing where I query the database, use Groovy to loop through and gather the data I need, and execute the validation web service with the results from the database call.
Here is my code:
response = context.expand('${JDBC Get User Task#ResponseAsXml}')
String userTaskId
int r = 1
def root = new XmlSlurper().parseText(response)
tc = testRunner.testCase
ts = tc.testSteps["Get usertask by id"]
root.ResultSet.Row.each{ row ->
log.info "Data for row: " + r.toString()
userTaskId = row["USER_TASKS.USER_TASK_ID"]
tc.setPropertyValue("result", userTaskId)
ts.run(testRunner, context)
r++
}
The problem I'm having is that if 3 results are returned, the only one that gets executed is the 3rd time into the validation web service.

How do you use lua in redis to return usable result to nodejs

one of the module i am implementing for my mobile app api is to get all outstanding notifications from , submitting username.
i used a list called username:notifications to store all outstanding id of notifications.
For example, in my test case, ['9','10',11'] is the result after calling for
lrange username:notifications 0 -1
So i wrote a lua script to get lrange and for each result,
hgetall notification:id
And for some reason, lua could not send the table, result to nodejs in usable state. Wondering if anyone
has a solution for multiple hgetall requests and returning them to nodejs
Here goes the rest of the code:
-- #KEYS: "username"
-- #ARGV: username
-- gets all fields from a hash as a dictionary
local hgetall = function (key)
local bulk = redis.call('HGETALL', key)
local result = {}
local nextkey
for i, v in ipairs(bulk) do
if i % 2 == 1 then
nextkey = v
else
result[nextkey] = v
end
end
end
local result = {}
local fields = redis.call('LRANGE' , ARGV[1], 0,-1)
for i, field in ipairs(fields) do
result[field] = hgetall('notification:'..field)
end
return result
You cannot return a "dictionary" from a Lua script, it is not a valid Redis type (see here).
What you can do is something like this:
local result = {}
local fields = redis.call('LRANGE' , ARGV[1], 0, -1)
for i=1,#fields do
local t = hgetall('notification:' .. fields[i])
result[#result+1] = fields[i]
result[#result+1] = #t/2
for j=1,#t do
result[#result+1] = t[j]
end
end
return result
The result is a simple list with this format:
[ field_1, nb_pairs_1, pairs..., field_2, nb_pairs_2, ... ]
You will need to decode it in your Node program.
EDIT: there is another solution, probably simpler in your case: encode the result in JSON and return it as a string.
Just replace the last line of your code by:
return cjson.encode(result)
and decode from JSON in your Node code.

Resources