If response contains the word 'any' then match response contains is failing - karate

Let's say if I am having a scenario like
Scenario: Call a Get API and validate the response
Given path 'myteam'
When method get
Then status 201
And print response
And match response contains { teamFeature: 'pick any feature'}
And my API response is
{
"id": "6c0377cd-96c9-4651-bcc8-0c9a7d962bc3",
"teamFeature": "pick any feature"
}
Then I am getting the error like
example.feature:19 - javascript evaluation failed: feature'}, :1:9 Missing close quote
feature'}
^ in at line number 1 at column number 9
If my API response does not contain the word 'any' and I change the match statement then it is working fine. Looks like I need to escape the the word 'any' somehow.
May I know how can I escape the word 'any'?
Not sure if this is a bug in Karate.
Tried to call
com.intuit.karate.Match match = new com.intuit.karate.Match("pick any feature");
System.out.println(match.contains("pick any feature"));
And received following error
Exception in thread "main" java.lang.RuntimeException: javascript
evaluation failed: pick any feature, :1:5 Expected ; but found
any pick any feature
^ in at line number 1 at column number 5 at com.intuit.karate.ScriptBindings.eval(ScriptBindings.java:152) at
com.intuit.karate.ScriptBindings.updateBindingsAndEval(ScriptBindings.java:142)
at
com.intuit.karate.ScriptBindings.evalInNashorn(ScriptBindings.java:127)
at com.intuit.karate.Script.evalJsExpression(Script.java:423) at
com.intuit.karate.Script.evalKarateExpression(Script.java:337) at
com.intuit.karate.Script.evalKarateExpression(Script.java:203) at
com.intuit.karate.Match.(Match.java:67) at
com.intuit.karate.Match.(Match.java:53)

Yes this is a bug in Karate, we've opened an issue: https://github.com/intuit/karate/issues/678
The workaround suggested by #BabuSekaran will work:
* def response = { foo: 'a any b' }
* def temp = { foo: 'a any b' }
* match response contains temp

Related

Error saying "Expecting value: line 1 column 1 (char 0) " when retrieving venue for the tip with the greatest number of agree counts

I am using foursquare api to retrieve the venue for the tip with the greatest number of agree counts using requests library in jupyterLab but I am getting this error "Expecting value: line 1 column 1 (char 0)". I am new to using api calls so please help me on how to fix this error. Below is my code:
tip_id = '5ab5575d73fe2516ad8f363b' # tip id
# define URL
url = 'http://api.foursquare.com/v2/tips/{}?client_id={}&client_secret={}&v={}'.format(tip_id, CLIENT_ID, CLIENT_SECRET, VERSION)
# send GET Request and examine results
result=requests.get(url).json()
# .get(url).json()
print(result['response']['tip']['venue']['name'])
print(result['response']['tip']['venue']['location'])
error:
[Error

Karate - How to call multiple external features from a single main feature

Feature: Principal feature
Background:
* url 'http://example.com'
Scenario: Feature calling
* def inputTable = call read('input_table.feature')
* call read('my_call.feature') inputTable.inputTestData
where the data table file is:
//input_table.feature
Feature:TABLE_TEST
Scenario:TABLE_TEST
* table inputTestData
|inputName|outputName|
|requestA|responseA|
this throw me an error of:
ERROR com.intuit.karate - feature call failed: .../input_table.feature
arg: null
input_table.feature:3 - evaluation (js) failed: requestA, javax.script.ScriptException: ReferenceError: "requestA" is not defined in <eval> at line number 1
stack trace: jdk.nashorn.api.scripting.NashornScriptEngine.throwAsScriptException(NashornScriptEngine.java:470)
but instead if i call the my_call feature with the data table defined inside in the Examples field it works correctly.
Any help?
There's a subtle difference between Examples and table. Maybe you meant to do this:
* table inputTestData
|inputName|outputName|
|'requestA'|'responseA'|
Read the docs: https://github.com/intuit/karate#table

Download a page doesn't return a status code

I have found a page I need to download that doesn't include an http status code in the returned headers. I get the error: ParseError: ('non-integer status code', b'Tag: "14cc1-5a76434e32f9e"') which is obviously accurate. But otherwise the returned data is complete.
I'm just trying to save the page content manually in a call back: afilehandle.write(response.body) sort of thing. It's a pdf. Is there a way I can bypass this and still get the contents of the page?
The returned example that also crashed fiddler. The first thing in the header is Tag.
Tag: "14cc1-5a76434e32f9
e"..Accept-Ranges: bytes
..Content-Length: 85185.
.Keep-Alive: timeout=15,
max=100..Connection: Ke
ep-Alive..Content-Type:
application/pdf....%PDF-
1.4.%ÓôÌá.1 0 obj.<<./Cr
eationDate(D:20200606000
828-06'00')./Creator(PDF
sharp 1.50.4740 \(www.pd
fsharp.com\))./Producer(
PDFsharp 1.50.4740 \(www
.pdfsharp.com\)).>>.endo
bj.2 0 obj.<<./Type/Cata
log./Pages 3 0 R.>>.endo
bj.3 0 obj.<<./Type/Page
s./Count 2./Kids[4 0 R 8
0 R].>>.endobj.4 0 obj.
<<./Type/Page./MediaBox[
0 0 612 792]./Parent 3 0
R./Contents 5 0 R./Reso
urces.<<./ProcSet [/PDF/
Text/Ima.... etc
Note: For any not familiar with PDF file structure %PDF-1.4 and everything after is the correct format for a PDF document. Chrome downloads the PDF just fine even with the bad headers.
In the end, I modified the file twisted/web/_newclient.py directly to not throw the error, and use a weird status code that I could identify:
def statusReceived(self, status):
parts = status.split(b' ', 2)
if len(parts) == 2:
version, codeBytes = parts
phrase = b""
elif len(parts) == 3:
version, codeBytes, phrase = parts
else:
raise ParseError(u"wrong number of parts", status)
try:
statusCode = int(codeBytes)
except ValueError:
# Changes were made here
version = b'HTTP/1.1' #just assume it is what it should be
statusCode = 5200 # deal with invalid status codes later
phrase = b'non-integer status code' # sure, pass on the error message
# and commented out the line below.
# raise ParseError(u"non-integer status code", status)
self.response = Response._construct(
self.parseVersion(version),
statusCode,
phrase,
self.headers,
self.transport,
self.request,
)
And I set the spider to accept that status code.
class MySpider(Spider):
handle_httpstatus_list = [5200]
However, in the end I discovered the target site behaved correctly when accessed via https, so I ended up rolling back all the above changes.
Note the above hack would work, until you updated the library, at which point you would need to reapply the hack. But it could possibly get it done if you are desparate.

Standardized Error Codes - Objective-C

I'm trying to add error codes to one of my project like this:
typedef enum {
FSChatErrorChatManagerInUse = 101,
FSChatErrorFailedToRetrieveHeader = 202,
FSChatErrorFailedToGetCount = 303,
} FSChatErrorCode;
Then, send:
NSError * err = [NSError errorWithDomain:#"Failed To Get Count"
code:FSChatErrorFailedToGetCount
userInfo:nil];
So when notified of an error, you can see what kind it is:
if (err.code == FSChatErrorFailedToGetCount) {
// do stuff
}
Question
Is there some sort of standard error code syntax or numbering I should follow? I'm having a hard time finding a reference.
This page has a nice discussion of this subject:
Like exit status codes, an NSError -code signals the nature of the
problem. These status codes are defined within a particular error
domain, in order to avoid overlap and confusion. These status codes
are generally defined by constants in an enum.
For example, in the NSCocoaErrorDomain, the status code for an error
caused by NSFileManager attempting to access a non-existant file is 4,
as defined by NSFileNoSuchFileError. However, 4 in NSPOSIXErrorDomain
refers to a POSIX EINTR, or "interupted function" error.
So, since you're using your own error domain, you can create whatever error codes you want. By the way, in your example you seem to be misusing the domain value: it's not meant to contain an error message.Use userInfo[NSLocalizedDescriptionKey] for that.

What is the standard code to check for valid/existing id in database-backed view in web2py?

In web2py, suppose I have the following url:
www.example.com/customer/view/1
Which is backed by a view() function in the customer controller and displays the customer with id of 1 from a database.
In the view function I want to handle the following error cases:
No argument is passed (/customer/view/) -> raise 404
A non-integer argument is passed (/customer/view/apple) -> raise 404
An integer argument is passed but does not exist in database (/customer/view/999999) -> raise 404
An application error occurs such as cannot connect to database -> raise 500 exception
What is the standard/canonical/correct way to handle these cases in the controller function in way that returns the proper HTTP error? It's such a common scenario that I'd like to do it in a correct and succinct way every time.
This almost works except it doesn't distinguish between id not valid/existing errors and any other errors:
def view():
try:
customer = db(db.customer.id==request.args(0, cast=int)).select()[0]
except:
raise HTTP(404, 'Cannot find that customer')
return dict(customer=customer)
def view():
id = request.args(0, cast=int, otherwise=lambda: None)
customer = db(db.customer.id == id).select().first()
if not customer:
raise HTTP(404, 'Cannot find that customer' if id
else 'Missing/invalid customer ID')
return dict(customer=customer)
If the cast fails in request.args(), by default it will raise its own HTTP(404), but you won't have control over the message. So, you can instead use the otherwise argument to return None in that case. The database query will then return None if the arg is missing or a non-integer, or if the customer is not found in the database.