in the response of a request i have this content:
"comp":[
{
"type":"header",
"version":1,
"settings":
{"logo":"mylogo",
"logoPosition":"left",
"inverseLogosPosition":false,
"headerTitle":"My Report",
"headerTitlePosition":"left",
"pageBreak":false
}
},
I want to assert the content of settings.
i try this for example to assert the logoPosition = "left"
assert json.components.settings[0].logoPosition[0] == "left"
it's not working
This part is working well:
assert json.comp.type[0] == "header"
assert json.comp.version[0] == 1
Any help please, thank you
The json provided is invalid. You can use both paths:
assert slurped.comp.settings.logoPosition[0] == "left"
assert slurped.comp[0].settings.logoPosition == "left"
Full example:
import groovy.json.JsonSlurper
def json = '''{
"comp":[
{
"type":"header",
"version":1,
"settings": {
"logo":"mylogo",
"logoPosition":"left",
"inverseLogosPosition":false,
"headerTitle":"My Report",
"headerTitlePosition":"left",
"pageBreak":false
}
}
]}'''
def slurped = new JsonSlurper().parseText(json)
assert slurped.comp.settings.logoPosition[0] == "left"
assert slurped.comp[0].settings.logoPosition == "left"
It will just be logoPosition, not logoPosition[0]
Why not have some expected json as a string, convert it to a map with JsonSlurper, then compare these?
Related
I have two array list in that form:
def AllowedExtensions = [ '.mxf', '.mov', '.mp4']
def myPaths = [C:\Temp\Media\Media.c2v, C:\Temp\Media\Media.V2C, C:\Temp\Media\toto\test\巨塔の終わり.mp4, C:\Temp\Media\toto\toto.mxf]
I'm trying to build a new list mySelectedPath from myPaths only if it matches one of the extensions from AllowedExtensions
I'm looking for the groovy way to do it but can't get it working correctly.
AllowedExtensions.each { mySelectedPath = myPaths.findAll { it }}
Here is my expected result:
[C:\Temp\MediaNavigator\toto\toto.mxf, C:\Temp\MediaNavigator\toto\test\巨塔の終わり.mp4]
Thank you for any input !
Another solution is to use findResults
allowedExtensions.findResults { ext -> myPaths.find { it.endsWith ext } }
If you want multiple results per extension, try:
allowedExtensions.findResults { ext -> myPaths.findAll { it.endsWith ext } }.flatten()
def AllowedExtensions = [ '.mxf', '.mov', '.mp4']
def myPaths = [
'C:\\Temp\\Media\\Media.c2v',
'C:\\Temp\\Media\\Media.V2C',
'C:\\Temp\\Media\\toto\\test\\巨塔の終わり.mp4',
'C:\\Temp\\Media\\toto\\toto.mxf'
]
println myPaths.findAll { it.toLowerCase()[it.lastIndexOf('.')..-1] in AllowedExtensions }
Or regex-based:
def AllowedExtensions = [ '.mxf', '.mov', '.mp4']
def myPaths = ['C:\\Temp\\Media\\Media.c2v', 'C:\\Temp\\Media\\Media.V2C', 'C:\\Temp\\Media\\toto\\test\\巨塔の終わり.mp4', 'C:\\Temp\\Media\\toto\\toto.mxf']
def regex = /^.*\.(${AllowedExtensions.join( '|' ).replace( '.', '' )})$/
def res = myPaths.grep{ it ==~ regex }
assert res.toString() == '[C:\\Temp\\Media\\toto\\test\\巨塔の終わり.mp4, C:\\Temp\\Media\\toto\\toto.mxf]'
I need to take my output from the for loop below and add it to a single array. The list object can either be ["envName-inactive-1", "active-1", "inactive-1", "envName-active-1"] or ["envName-inactive-2", "", "", "envName-active-2"]
My code:
if (appendVersion) {
for (elements in list) {
test = (elements + "-" + branch)
println(test)
}
} else {
println(list)
}
output:
envName-inactive-1-v2
active-1-v2
inactive-1-v2
envName-active-1-v2
and
envName-inactive-2-v2
-v2
-v2
envName-active-2-v2
desired output:
["envName-inactive-1-v2", "active-1-v2", "inactive-1-v2", "envName-active-1-v2"]
and
["envName-inactive-2-v2", "", "", "envName-active-2-v2"]
You desired format seems to be json. In Jenkins you have option to use writeJSON to convert list to json format.
def branch = "v2"
def list = ["envName-inactive-1", "active-1", "inactive-1", "envName-active-1"]
def versionedList = list.collect{it ? it+'-'+branch : ''}
def json = writeJSON returnText: true, json: versionedList
println json
the same in plain groovy:
def branch = "v2"
def list = ["envName-inactive-1", "active-1", "inactive-1", "envName-active-1"]
def versionedList = list.collect{it ? it+'-'+branch : ''}
def json = new groovy.json.JsonBuilder(versionedList).toString()
println json
result:
["envName-inactive-1-v2","active-1-v2","inactive-1-v2","envName-active-1-v2"]
HI I have a simple function. Which internally calls db but during local testing it can't connect DB so for that I have wrote specific exception and I want do side effect for same but it's not working.
Here is my code
def support_issue_contact(message, message_headers):
# Check if reporter_email_address is present in message
logger = message_headers.get('logger')
reporter_email = message.get('reporter_email_address', None)
if reporter_email is None:
return None
elif validators.email(reporter_email):
# look up message in our contact table to see if it exists
rule = {
"lookup_documents": [{
"document_type": "hub",
"hub_table": "hubs",
"entity": "contact",
"lookup_key_path": "reporter_email_address"
}]
}
try:
retrieve_documents(message, rule)
except StaleEventException:
return None
# Catch the retrieve_documents function if no 'Item' exists in the response it gets from Dynamo
# If no 'Item' exists then no contact exists so it should create a new contact
except KeyError as valid_exception:
if 'Item' in valid_exception.args:
# validate context to see if it is on 'Item'
contact_message = {
"business_key": reporter_email,
"source_system": 'gsac',
"source_system_id": reporter_email,
"source_sequence": message.get('source_sequence'),
"email": reporter_email,
"full_name": message.get('reporter_display_name', ''),
"customer_domain":
derive_customer_domain(reporter_email),
"status": "ACTIVE",
"id": reporter_email
}
return {
"payload": contact_message,
"schema": "it-bdm/contact-schema-v3.5.json",
"type": "avi:hydra-gsac:contact:upsert",
}
elif ('payload' in valid_exception.args) or ('satellite_name' in valid_exception.args):
# This means that the item exists within the hubs so we don't want to do anything
return None
else:
raise valid_exception
# All other exceptions should be raised
except Exception as e:
logger.error(e.__str__())
raise e
else:
return None
And I want that retrieve_documents function should raise CustomKeyError so I wrote these way and both are not working.
class SupportIssueContactTest(unittest.TestCase):
raw_event = parse_json_file(os.path.join(DIR_TEST_DATA, 'support-issue', 'support_issue.json'))
transformed_event = parse_json_file(os.path.join(DIR_TEST_DATA, 'support-issue', 'transformed_support_issue.json'))
def test_support_issue_contact_context(self):
with mock.patch('src.datavault_helper.retrieve_documents') as retrieve_documents_mock:
retrieve_documents_mock.side_effect = CustomKeyError()
assert self.transformed_event == support_issue_contact(message=self.raw_event, message_headers={'logger': config.logger})
#mock.patch('src.datavault_helper.retrieve_documents')
def test_support_issue_contact_decorator(self, retrieve_documents_mock):
retrieve_documents_mock.side_effect = CustomKeyError()
assert self.transformed_event == support_issue_contact(message=self.raw_event,
message_headers={'logger': config.logger})
I figured out the answer.
def test_support_issue_contact_context(self):
with mock.patch('path_of_function_where_it_is_called_for_mock') as retrieve_documents_mock:
retrieve_documents_mock.side_effect = CustomKeyError()
assert self.transformed_event == support_issue_contact(message=self.raw_event, message_headers={'logger': config.logger})
I am trying to create a groovy script assertion in SoapUI. In the response, I and trying to pull a field called written. however there are +15 of these fields.
I is possible to add the XPath to the XmlSlurper to find the exact written fields I want to assert against.
Looking at the XML response below, I would like to assert the value in b:premium\written. not the one from the b:other. Given there are 15+ b:written fields i would like to assert the value using the xpath.
XML Response:
<s:Body>
<NewRateResponse>
<NewRateResult>
<b:policies>
<b:other>
<b:written>00.00</b:written>
</b:other>
<b:premium>
<b:written>31.21</b:written>
</b:premium>
</b:policies>
</NewRateResult>
</NewRateResponse>
</s:Body>
Assertion Code:
import org.junit.Assert
def response = messageExchange.getResponseContent()
def xml = new XmlSlurper().parseText(response)
def nodePremium = xml.'**'.find { it.name() == 'written'}
Assert.assertEquals(00.01, nodePremium.toDouble(),0)
I believe the area we need to change is def nodePremium = xml.'**'.find { it.name() == 'written'}. to be something like def nodePremium = xml.'**'.find { it.name() == 'premium\written'} but that does not work for me.
assert xml.'**'.find { it.name() == 'premium'}.written.text() as Double == 31.20
I am new to groovy code. I have a map like this
response = {"data":{"--class":"java.util.HashMap","Enabled":false,"Adult":"[recursive reference removed]","TVMA":"[recursive reference removed]","Locks":[false,false,false,false,false,false],"PINEnabled":false,"AdvisoryLocks":[false,false,false,false,false,false,false,false,false,false,false,false],"safeSearch":"[recursive reference removed]","RatingLocks":[false,false,false,false,false,false]},"success":true}
Using groovy code I want to check the presence of the following keys:
Enabled,
Adult,
TVMA,
Locks,
PINEnabled,
AdvisoryLocks,
safeSearch,
RatingLocks,
I am using the following code:
for ( data in response.data ) {
println("-----------------------------------------")
assertNotNull(data.Enabled)
assertNotNull(data.Adult)
;;;;;;
.......
}
Am getting groovy.lang.MissingPropertyException: No such property: Enabled
How can I check the presence of the above keys from response map using groovy?
I think you can find keys value from the Json like below.
def slurper = new JsonSlurper()
def result = slurper.parseText(response)
assert result.data.Enabled != null
assert result.data.Enabled != ""
assert result.data.Adult != null
assert result.data.Adult != ""
I hope that will help you :)
How about using good'ol regexp?
String response = '{"data":{"--class":"java.util.HashMap","Enabled":false,"Adult":"[recursive reference removed]","TVMA":"[recursive reference removed]","Locks":[false,false,false,false,false,false],"PINEnabled":false,"AdvisoryLocks":[false,false,false,false,false,false,false,false,false,false,false,false],"safeSearch":"[recursive reference removed]","RatingLocks":[false,false,false,false,false,false]},"success":true}'
assert [ 'Enabled', 'Adult', 'TVMA',,,, ].every{ response =~ /"$it":/ }