SpringMVC/MockMVC/ jsonpath compare list of Integers - spring-mvc

I have searched online but can't find why or how to fix it.
Problem:
My JUnit test pulls a list of user id's from a REST-API.
However, I can't seem to assert the contents of the response...
API Response:
[
{"userId":1458548702},
{"userId":1458548703},
{"userId":1458548704},
{"userId":1458548706},
{"userId":1458548707}
]
Assertion Code:
List<Integer> expectedIds = ....
ResultActions result = ...
//JSONArray and expectedIds are the same length
result.andExpect(
MockMvcResultMatchers.jsonPath(
"$.*",
Matchers.hasSize(expectedIds.size())
)
);
//Below Fails:
result.andExpect(
MockMvcResultMatchers.jsonPath(
"$[*].userId",
Matchers.containsInAnyOrder(expectedIds)
)
);
Error Message:
java.lang.AssertionError: JSON path "$[*].userId"
Expected: iterable over [<[1458548702, 1458548703, 1458548704, 1458548706, 1458548707]>] in any order
but: Not matched: <1458548702>
at org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:20)
...
Libraries I'm using:
com.jayway.jsonpath json-path 2.0.0
com.jayway.jsonpath json-path-assert 2.0.0
org.mockito mockito-core 1.10.19
org.hamcrest hamcrest-all 1.3

Related

Failed when parsing body as json - call Rasa API with request.post()

I'm writing a function to call Rasa API for intent prediction. Here is my code:
def run_test():
url = "http://localhost:5005/model/parse"
obj = {"text": "What is your name?"}
response = requests.post(url, data=obj)
print(response.json())
I also start Rasa server with this command: rasa run -m models --enable-api --cors "*" --debug
And here is what I got from Rasa server terminal:
In the terminal that I excuted run_test(), I got this result:
{'version': '2.7.1', 'status': 'failure', 'message': 'An unexpected error occurred. Error: Failed when parsing body as json', 'reason': 'ParsingError', 'details': {}, 'help': None, 'code'
: 500}
Anybody help me to solve this problem? Thank you very much!
I found the solution:
Only need to use json.dumps() the object, because object in Python is different than object in json.
def run_test():
url = "http://localhost:5005/model/parse"
obj = {"text": "What is your name?"}
response = requests.post(url, data=json.dumps(obj))
print(response.json())

RobotScript - Catch Python Code Exception

We have a following code in Python
def function1()
...........
raise Exception ..
...............
return 0
Robot script:
${STATUS}= function1
Can anyone please let me know how in Robot script we can catch the return code / exception and branch accordingly?
Run Keyword And Return Status will return a boolean true/false did the enclose keyword succeed.
Run Keyword And Ignore Error returns a tuple of two values - the 1st is the string "PASS" or "FAIL" depending did your keyword succeed or not; the second - the keyword's return value if it passed, or any error messages if not.
Thus surround your keyword with one of these 2 - it really boils down to do you care about the returned value in success or the error in failure - and work with the returned values.
${passed}= Run Keyword And Return Status function1
Run Keyword If ${passed} Action When Passed ELSE Different Action
${rc} ${msg} Run Keyword And Ignore Error function1
Run Keyword If "${rc}" == 'PASS' Log The keyword returned the value: ${msg}
... ELSE Log The keyword failed with the message: ${msg}

Idiomatic/Groovy way to add two maps, either of which may be null

I have the following map:
configs = [
common : [
foo : '123',
bar : '456'
],
dev : [
foo : '789',
bar : '012'
],
test : null
]
When I add dev to common, it works great - the values from common are overridden by the values from dev. Just what I want.
dev = configs['common'] + configs['dev']
println dev
// --> [foo:789, bar:012]
However, if I try the same with test, I get the following error:
groovy.lang.GroovyRuntimeException: Ambiguous method overloading for method java.util.LinkedHashMap#plus.
Cannot resolve which method to invoke for [null] due to overlapping prototypes between:
[interface java.util.Collection]
[interface java.util.Map]
I can make it work by doing something like the following:
test = [:]
test = configs['common']==null ? test : test + configs['common'] // First add common bits
test = configs['test']==null ? test : test + configs['test'] // Then override with environment specific bits
println test
// --> [foo:123, bar:456]
But this seems ugly and bloated.
Can someone with better Groovy-fu show me a nicer way? Thanks!
You can use Elvis operator to bring an empty map to the equation when config['test'] == null. Consider the following example:
def configs = [
common : [
foo : '123',
bar : '456'
],
dev : [
foo : '789',
bar : '012'
],
test : null
]
def dev = configs['common'] + (configs['dev'] ?: [:])
println dev
def test = configs['common'] + (configs['test'] ?: [:])
println test
Output:
[foo:789, bar:012]
[foo:123, bar:456]
You can use it whenever you expect that one value can be represented by null.

OpenStack SDK - How to create image with Kernel id and Ramdisk parameters?

I've been trying to create an OpenStack image informing the Kernel Id and Ramdisk Id, using the OpenStack Unified SDK (https://github.com/openstack/python-openstacksdk), but without success. I know this is possible, because the OpenStack CLI have this parameters, as shown on this page (http://docs.openstack.org/cli-reference/glance.html#glance-image-create), where the CLI have the "--kernel-id" and "--ramdisk-id" parameters. I've used this parameter in the terminal and confirmed they work, but I need to use them in python.
I'm trying to use the upload_method, as described here http://developer.openstack.org/sdks/python/openstacksdk/users/proxies/image.html#image-api-v2 but I can't get the attrs parameter right. Documentation only say it is suposed to be a dictionary. Here is the code I'm using
...
atrib = {
'properties': {
'kernel_id': 'd84e1f2b-8d8c-4a4a-8858-77a8d5a93cb1',
'ramdisk_id': 'cfef18e0-006e-477a-a098-593d43435a1e'
}
}
with open(file) as fimage:
image = image_service.upload_image(
name=name,
data=fimage,
disk_format='qcow2',
container_format='bare',
**atrib)
....
And here is the error I'm getting:
File "builder.py", line 121, in main
**atrib
File "/usr/lib/python2.7/site-packages/openstack/image/v2/_proxy.py", line 51, in upload_image
**attrs)
File "/usr/lib/python2.7/site-packages/openstack/proxy2.py", line 193, in _create
return res.create(self.session)
File "/usr/lib/python2.7/site-packages/openstack/resource2.py", line 570, in create
json=request.body, headers=request.headers)
File "/usr/lib/python2.7/site-packages/keystoneauth1/session.py", line 675, in post
return self.request(url, 'POST', **kwargs)
File "/usr/lib/python2.7/site-packages/openstack/session.py", line 52, in map_exceptions_wrapper
http_status=e.http_status, cause=e)
openstack.exceptions.HttpException: HttpException: Bad Request, 400 Bad Request
Provided object does not match schema 'image': {u'kernel_id': u'd84e1f2b-8d8c-4a4a-8858-77a8d5a93cb1', u'ramdisk_id': u'cfef18e0-006e-477a-a098-593d43435a1e'} is not of type 'string' Failed validating 'type' in schema['additionalProperties']: {'type': 'string'} On instance[u'properties']: {u'kernel_id': u'd84e1f2b-8d8c-4a4a-8858-77a8d5a93cb1', u'ramdisk_id': u'cfef18e0-006e-477a-a098-593d43435a1e'}
Already tried to use the update_image method, but without success, passing kernel id and ramdisk id as a strings creates the instance, but it does not boot.
Does anyone knows how to solve this?
what the version of the glance api you use?
I have read the code in openstackclient/image/v1/images.py, openstackclient/v1/shell.py
## in shell.py
def do_image_create(gc, args):
...
fields = dict(filter(lambda x: x[1] is not None, vars(args).items()))
raw_properties = fields.pop('property')
fields['properties'] = {}
for datum in raw_properties:
key, value = datum.split('=', 1)
fields['properties'][key] = value
...
image = gc.images.create(**fields)
## in images.py
def create(self, **kwargs):
...
for field in kwargs:
if field in CREATE_PARAMS:
fields[field] = kwargs[field]
elif field == 'return_req_id':
continue
else:
msg = 'create() got an unexpected keyword argument \'%s\''
raise TypeError(msg % field)
hdrs = self._image_meta_to_headers(fields)
...
resp, body = self.client.post('/v1/images',
headers=hdrs,
data=image_data)
...
and openstackclient/v2/shell.py,openstackclient/image/v2.images.py(and i have debuged this too)
## in shell.py
def do_image_create(gc, args):
...
raw_properties = fields.pop('property', [])
for datum in raw_properties:
key, value = datum.split('=', 1)
fields[key] = value
...
image = gc.images.create(**fields)
##in images.py
def create(self, **kwargs):
"""Create an image.""
url = '/v2/images'
image = self.model()
for (key, value) in kwargs.items():
try:
setattr(image, key, value)
except warlock.InvalidOperation as e:
raise TypeError(utils.exception_to_str(e))
resp, body = self.http_client.post(url, data=image)
...
it seems that, you can create a image use your way in version 1.0, but in version 2.0, you should use the kernel_id and ramdisk_id as below
atrib = {
'kernel_id': 'd84e1f2b-8d8c-4a4a-8858-77a8d5a93cb1',
'ramdisk_id': 'cfef18e0-006e-477a-a098-593d43435a1e'
}
but the OpenStack SDK seems it can't trans those two argments to the url (because there is no Body define in openstack/image/v2/image.py. so you should modify the OpenStack SDK to support this.
BTW, the code of OpenStack is a little different from it's version, but many things are same.

Custom command result

When invoking a custom command, I noticed that only the logs are displayed. For example, if my Custom Comand script contains a retrun statement return "great custom command", I can't find it in the result. Both in API Java client or shell execution cases.
What can I do to be able to retrieve that result at the end of an execution?
Thanks.
Command definition in service description file:
customCommands ([
"getText" : "getText.groovy"
])
getText.groovy file content:
def text = "great custom command"
println "trying to get a text"
return text
Assuming that you service file contains the following :
customCommands ([
"printA" : {
println "111111"
return "222222"
},
"printB" : "fileB.groovy"
])
And fileB.groovy contains the following code :
println "AAAAAA"
return "BBBBBB"
Then if you run the following command : invoke yourService printA
You will get this :
Invocation results:
1: OK from instance #1..., Result: 222222
invocation completed successfully.
and if you run the following command : invoke yourService printB
You will get this :
Invocation results:
1: OK from instance #1..., Result: AAAAAA
invocation completed successfully.
So if your custom command's implementation is a Groovy closure, then its result is its return value.
And if your custom command's implementation is an external Groovy file, then its result is its last statement output.
HTH,
Tamir.

Resources