Filter a json with a variable inline not correct - karate

I create a script to filter a list user that not include the specified one. But when I tried:
* def userId = response.data[0].id
* def filter = ''
* def users = get[0] response.data[?(#.id!="bd04b9f0-c254-4f23-9fed-6a0300692bbb")]
* print users.id
is correct
But I want re-use a value form previous step like:
* def userId = response.data[0].id
* def filter = 'bd04b9f0-c254-4f23-9fed-6a0300692bbb'
* def users = get[0] response.data[?(#.id!="#(filter)")]
* print users.id
Is incorrect

Read the docs please: https://github.com/intuit/karate#jsonpath-filters
* def users = karate.jsonPath(response, "$.data[?(#.id!='" + filter + "')]")[0]

Related

I would like to check whether a string is within a predefined list in my Karate Scenario

The scenarios work if I create individual ones for each permutation however I would like to avoid having to read the file multiple times considering it can become quite a large file.
Scenario Outline: Mass_A is correct for STD and PCE
* def row =
"""
{
Artikeltyp: '<Artikeltyp>',
MinBestellmengeEinheit: '<MinBestellmengeEinheit>',
Mass_A: '<Mass_A>'
}
"""
* def tempArtikeltyp = '<Artikeltyp>'
* def tempMinBestellmengeEinheit = '<MinBestellmengeEinheit>'
* def tempMass_A = '<Mass_A>'
* def listMinBestTypes = ['PCE','PR','DZN']
* def expected = (tempArtikeltyp == 'STD' && (karate.match(listMinBestTypes,tempMinBestellmengeEinheit).pass) && (tempMass_A.length <= 0)) ? 'Mass_A is NOT populated for STD and PCE' : 'Mass_A is correct for STD and PCE'
* match expected == karate.info.scenarioName
Examples:
| read('input.csv')|
Any guidance would be much appreciated.
Here is a suggestion. Please re-think your entire approach. Start with the CSV file, convert it to JSON and then run all the permutations or combinations you want. Example below:
Scenario:
* def isValid = function(x){ return true }
* def data = read('input.csv')
* match each data == '#? isValid(_)'

Is it possible to put EXECUTE IMMEDIATE and USING into Variable in Python

This is a continuous of previous post .
How to get result from BigQuery based on user input parameters .
I tried to use EXECUTE IMMEDIATE and USING as these article say.
https://cloud.google.com/bigquery/docs/parameterized-queries
https://towardsdatascience.com/how-to-use-dynamic-sql-in-bigquery-8c04dcc0f0de
But when I run the sql , I got syntax error . I'd like to get my sql checked . I guess this error is caused by the line breaks but I want to do that for the readability . Sorry for my poor coding skill . Could you give me advice ??
I'm little bit worry about BigQuery doesn't support dynamic parameter in Python. Because the article above seems to use these statement in Console not in Python .
The error
File "/srv/main.py", line 14 SELECT EXISTS(SELECT 1
SyntaxError: invalid syntax
SQL
query = """EXECUTE IMMEDIATE format("""
SELECT EXISTS(SELECT 1
FROM `test-266778.conversion_log.conversion_log_2020*` as p
WHERE p.luid = #request_luid AND orderid != '' limit 1000)""")"""
USING "request_luid" as request_luid;
/home/user/api_dev/main.py
from flask import Flask, request, jsonify
from google.cloud import bigquery
app = Flask(__name__)
#app.route('/')
def get_request():
request_luid = request.args.get('luid') or ''
client = bigquery.Client()
query = """EXECUTE IMMEDIATE format("""
SELECT EXISTS(SELECT 1
FROM `test-266778.conversion_log.conversion_log_2020*` as p
WHERE p.luid = #request_luid AND orderid != '' limit 1000)""")"""
USING "request_luid" as request_luid;
job_config = bigquery.QueryJobConfig(
query_parameters=[
bigquery.ScalarQueryParameter("request_luid", "STRING", request_luid)
]
)
query_job = client.query(query, job_config=job_config)
query_res = query_job.result()
first_row = next(iter(query_job.result()))
for row in query_res:
return str(row)
#return jsonify({request_luid:query_res.total_rows})
if __name__ == "__main__":
app.run()
You can try this:
def get_request():
request_luid = request.args.get("luid") or ""
client = bigquery.Client()
query = """SELECT EXISTS(
SELECT 1
FROM `test-266778.conversion_log.conversion_log_2020*` as p
WHERE p.luid = {}
AND p.orderid is not null limit 1000)""".format(request_luid)
query_job = client.query(query)
query_res = query_job.result()
first_row = next(iter(query_job.result()))
for row in query_res:
return str(row)
Notes: If the luid is non-numeric, then use '{}'.
You can try this:
EXECUTE IMMEDIATE
"""SELECT EXISTS(SELECT 1 FROM `test-266778.conversion_log.conversion_log_2020*` WHERE luid = ? AND orderid is not null limit 1000)"""
USING
"string-value";
For numeric input value, don't use double quotes

Karate: Remove a dynamic element from from JSON

* def res1 = {"member":{"muid":"MBR1"},"part":[{"PID":"M123"},{"supportedMembers":[{"muid":"MBR3","status":{"code":"A"}},{"muid":"MBR2","status":{"code":"I"}}]}]}
* def res2 = {"members":[{"member":{"muid":"MBR2","test":[{"EID":"E123"}]}},{"member":{"muid":"MBR3","test":[{"EID":"E123"}]}}]}
Karate: Match array elements of two different JSON
I have another requirement which is related to my earlier post.
* def id = res1.member.muid
I want to remove id from res2 response, which can be any where in res2.members.member, and do the matching with res1 to see the presence of muids
I tried something like below, but its not working:
* karate.remove('$res2.members[*]..muid','$.muid[id]')
Sample Code:
Feature: Validation
Scenario:
* def res1 = {"member":{"muid":"MBR1"},"part":[{"PID":"M123"},{"supportedMembers":[{"muid":"MBR3","status":{"code":"A"}},{"muid":"MBR2","status":{"code":"I"}}]}]}
* def res2 = {"members":[{"member":{"muid":"MBR2","test":[{"EID":"E123"}]}},{"member":{"muid":"MBR3","test":[{"EID":"E123"}]}}]}
* def id = res1.member.muid
* def res2ids = $res2.members[*]..muid
* def data2 = karate.mapWithKey(res2ids, 'muid')
* print data2
* def res2ids = karate.jsonPath(data2, "$[?(#.muid != '" + id+ "')]")
* def res2ids = $res2ids[*]..muid
* print res2ids
* match res1.part[1].supportedMembers[*].muid contains only res2ids

Pivot in custom module odoo 9

I'm try create pivot in custom module, but get error TypeError:
init() takes exactly 1 argument (2 given)
class ReportMyModuleUser(models.Model):
_name = "report.my.module.user"
_description = "My module"
_auto = False
name = fields.Char(string = 'Name')
date = fields.Datetime(string = 'Date')
user_id = fields.Many2one('res.users', 'User')
def _select(self):
select_str = """
SELECT
pn.name,
pn.date,
pn.user_id
"""
return select_str
def _group_by(self):
group_by_str = """
GROUP BY
pn.name
"""
return group_by_str
def init(self):
print(self)
tools.drop_view_if_exists(self._cr, self._table)
self._cr.execute("""
CREATE view %s as
%s
FROM my_table pn
%s
""" % (self._table, self._select(), self._group_by()))
Any solution where is problem?
Maybe is problem in .xml file? I don't have idea.
You need to manage one api on above of the init as like below.
#api.model_cr
def init(self):
print(self)
tools.drop_view_if_exists(self._cr, self._table)
self._cr.execute("""
CREATE view %s as
%s
FROM my_table pn
%s
""" % (self._table, self._select(), self._group_by()))
Your issue will resolve.
Or you can write your code in OLD api as below.
def init(self, cr):
print(self)
tools.drop_view_if_exists(cr, self._table)
cr.execute("""
CREATE or REPLACE VIEW report_my_module_user as
%s
FROM my_table pn
%s
""" % (self._select(), self._group_by()))

PyQt exclusive OR in sql query

How can I make that if my first search shows results it doesn't do the second part of the query, but stops and displays results? I tried something like this, but it just gives me blank window and it's pretty chaotic:
def test_update(self):
projectModel = QSqlQueryModel()
projectModel.setQuery("""SELECT * FROM pacijent WHERE prezime = '%s' OR (prezime, 3) = metaphone('%s', 3) OR LEVENSHTEIN(LOWER(prezime), '%s') < 3 AND NOT (prezime = '%s' AND (prezime, 3) = metaphone('%s', 3) AND LEVENSHTEIN(LOWER(prezime), '%s') < 3)""" % (str(self.lineEdit.text()), str(self.lineEdit.text()), str(self.lineEdit.text()), str(self.lineEdit.text()), str(self.lineEdit.text()), str(self.lineEdit.text())))
global projectView
projectView = QtGui.QTableView()
projectView.setModel(projectModel)
projectView.show()
So, if it finds the exact value of attribute "prezime" it should display it, but if it doesn't it should call for more advance saerch tactics, such as metaphone and levenshtein.
EDIT:
I got it working like this:
ef search_data(self):
myQSqlQueryModel = QSqlQueryModel()
query = QSqlQueryModel()
global myQTableView
myQTableView = QtGui.QTableView()
querySuccess = False
for queryCommand in [""" SELECT * FROM "%s" WHERE "%s" = '%s' """ % (str(self.search_from_table_lineEdit.text()), str(self.search_where_lineEdit.text()), str(self.search_has_value_lineEdit.text()))]:
myQSqlQueryModel.setQuery(queryCommand)
if myQSqlQueryModel.rowCount() > 0:
myQTableView.setModel(myQSqlQueryModel)
myQTableView.show()
querySuccess = True
break
if not querySuccess:
query.setQuery(""" SELECT * FROM "%s" WHERE METAPHONE("%s", 3) = METAPHONE('%s', 3) OR LEVENSHTEIN("%s", '%s') < 4 """ % (str(self.search_from_table_lineEdit.text()), str(self.search_where_lineEdit.text()), str(self.search_has_value_lineEdit.text()), str(self.search_where_lineEdit.text()), str(self.search_has_value_lineEdit.text())))
global var
var = QtGui.QTableView()
var.setModel(query)
var.show()
After your query success, your can check your data in model if have any row count in this method. And your for loop to get many query;
def testUpdate (self):
myQSqlQueryModel = QtSql.QSqlQueryModel()
myQTableView = QtGui.QTableView()
querySuccess = False
for queryCommand in ["YOUR QUERY 1", "YOUR QUERY 2"]:
myQSqlQueryModel.setQuery(queryCommand)
if myQSqlQueryModel.rowCount() > 0:
myQTableView.setModel(myQSqlQueryModel)
myQTableView.show()
querySuccess = True
break
if not querySuccess:
QtGui.QMessageBox.critical(self, 'Query error', 'Not found')