OpenCSV - parse collection in header - groovy

I have a working setup (btw. using groovy) for OpenCSV HeaderColumnNameMappingStrategy and MyCustomBean.
def file = new FileReader(new File("sample.csv"))
def csvReader = new CSVReader(file)
def strategy = new HeaderColumnNameMappingStrategy<MyCustomBean>()
strategy.setType(MyCustomBean)
I am curious, whether it is possible to parse any collection (I guess a map) from header.
Sample csv
priority,subject,description,customFields[4]
1,first,foo,X-7
2,second,hoo,X-8
Mapped bean
class MyCustomBean {
def subject
def description
def priority
def customFields
}

Related

Testing flask_wtf/wtforms with pytest

I'd like to test a POST route that processes a non-trivial form (by working with flask.request.form). I didn't really find a good tutorial for this somehow as most pass json data rather than form (or is it the same?).
I tried to write the code in the following way:
import pytest
import app #app.app is the Flask app
#pytest.fixture
def client():
app.app.config['TESTING'] = True
with app.app.test_client() as client:
with app.app.app_context():
yield client
def test_route_webapp_post(client):
form = app.forms.ImputeForm.make_form(data_dict=app.data_dictionary.data_dict,
numeric_fields=app.binaries_dict['numeric_mappers'].keys(),
recordname2description=app.binaries_dict['recordname2description'])
rv = client.post('/web_app',form=form)
assert rv.status_code==200
The form is generated dynamically and I don't always know ahead of time what are the fields:
from flask_wtf import FlaskForm
from wtforms import SelectField, DecimalField, BooleanField
class ImputeForm(FlaskForm):
#classmethod
def make_form(cls, data_dict, numeric_fields, recordname2description, request_form=None):
for key in numeric_fields:
setattr(cls, key, DecimalField(id=key, label=recordname2description[key].split('(')[0]))
setattr(cls, 'mask_' + key, BooleanField(label='mask_' + key))
for key in data_dict:
setattr(cls, key, SelectField(id=key, label=recordname2description[key],
choices=[(-1, 'None selected')]+list(data_dict[key].items())))
setattr(cls, 'mask_' + key, BooleanField(label='mask_' + key))
instance = cls(request_form)
return instance
But this doesn't really work as I can't make a form inside the test case and get
E RuntimeError: Working outside of request context.
E
E This typically means that you attempted to use functionality that needed
E an active HTTP request. Consult the documentation on testing for
E information about how to avoid this problem.
So what is the proper approach to testing my form (in particular I am ok with sending an empty one)?
The correct way is to create a python dictionary and pass it as "data", not to try to create a form.
In particular case this involved making a new function:
def make_from_data( data_dict, numeric_fields):
data = dict()
for key in numeric_fields:
data[key]='234'
data['mask_' + key]='y'
for key in data_dict:
data[key]=-1
data['mask_' + key]='y'
return data
and passing it as follows:
def test_route_webapp_post(client):
data = make_from_data(data_dict=app.data_dictionary.data_dict,
numeric_fields=app.binaries_dict['numeric_mappers'].keys())
rv = client.post('/web_app',data=data)
assert rv.status_code==200

how can I get value from json object in groovy

def RawRecordsDateRangeResponse = context.expand('${getRawRecordsForDateRange#Response}')
log.info RawRecordsDateRangeResponse
My response is:
{"2018-09-03":"https://dhap-dconnect-telemetry-data-dev2.s3.amazonaws.com/ULT/d83350d2-af56-11e8-b612-0242ac11001118/temperature/raw-2018-09-03.json"}
Here I want to get the value from the json response key as date.
Your response represents JSON document and it stores it in variable of type String. You can parse it using groovy.json.JsonSlurper class. Consider following example:
import groovy.json.JsonSlurper
def RawRecordsDateRangeResponse = context.expand('${getRawRecordsForDateRange#Response}')
def json = new JsonSlurper().parseText(RawRecordsDateRangeResponse)
def url = json.'2018-09-03'
println url
Output:
https://dhap-dconnect-telemetry-data-dev2.s3.amazonaws.com/ULT/d83350d2-af56-11e8-b612-0242ac11001118/temperature/raw-2018-09-03.json
If it's just the key of the JSON message you need rather than the value, you could use something like:
import groovy.json.JsonSlurper
def rawRecordsDateRangeResponse = '''{"2018-09-03":"https://dhap-dconnect-telemetry-data-dev2.s3.amazonaws.com/ULT/d83350d2-af56-11e8-b612-0242ac11001118/temperature/raw-2018-09-03.json"}'''
def json = new JsonSlurper().parseText(rawRecordsDateRangeResponse)
def date = json.collect({it.key})
print date
This produces [2018-09-03].

no such property: it for class

I am trying to retrieve a list of all instances of 'search' from a json response and set it so that any values that contains 'null' is changed to 0. However I am getting an error stating no such property: it for class. How can I fix this to ensure I get the code working so any instance of 'null' changes to 0?
import groovy.json.JsonSlurper
def response = messageExchange.response.responseContent
def json = new JsonSlurper().parseText(response)
def resultItems = json.xxx.xxx.items
def resultSearchCostGroup = json.xxx.xxx.xxx.search
int totalSearchCostGroup = resultSearchCostGroup.flatten().collect(it ?:0 ).sum()
Your last line should read
int totalSearchCostGroup = resultSearchCostGroup.flatten().collect { it ?:0 }.sum()

Node in the groovy. Could not find matching constructor for: groovy.util.Node(groovy.util.NodeList, java.lang.String)

def xmlRecords = new XmlParser().parseText(peopleString)
// println xmlRecords.person.subject_datas
println "123"
def datas = xmlRecords.person.subject_datas
def newNode = new Node(datas, 'subject_data')
def newSubNode = new Node(newNode, "subject_field_id", ["type", "integer"], "123max offer")
def newSubNode1 = new Node(newNode, "value", "1000")
def newNode2 = new Node(datas,"subject_data")
def newSubNode2 = new Node(newNode, "subject_field_id", ["type", "integer"], "123application Status")
def newSubNode21 = new Node(newNode, "value", "APPLIED")
Hi All,
I am face to a problem when I am trying to update a xml response.
I am using parseText to convert xmlstring to node. And then use the constructer to create a Node obj. new Node(NodeList, Object(name))
I got confused by the name which should use Object. When I put String here I got Could not find matching constructor for: groovy.util.Node(groovy.util.NodeList, java.lang.String). Do I need to convert String to Object? ?_?

How to save id using groovy from response?

in soapui my project is :
Project
|__Datasource
|__request
|__groovy_code
|__DatasourceLoop
My Datasource contains 100 lines, each one is a request with different parameters.
My groovy_code save the id from the response of the request.
When i run my project, it executes 100 requests without errors.
groovy_code save only the first id.
What i want is to save id for each request, so 100 ids in different variables at project level
Here is my groovy_code:
import groovy.json.JsonSlurper
def response = context.expand( '${login#Response#declare namespace ns1=\'https://elsian/ns/20110518\'; //ns1:login_resp[1]/ns1:item[1]/ns1:response[1]}' )
def slurper = new JsonSlurper()
def result = slurper.parseText(response)
log.info result.data.id
testRunner.testCase.testSuite.project.setPropertyValue("token_id", result.data.id)
Thank you for your help
I never use SOAPUI PRO and I don't have access to datasource testStep or even datasource loop.
However based on the project structure you're showing I suppose that for each time datasource loop founds a element in datasource it sends the flow to request step so request and groovy steps are executed on each iteration; due to this I think that the problem is that your groovy code is overriding each time the same property with a new value.
Then to solve this you can try adding some variable suffix to your property name to avoid override each time the property value. For example you can add to token_id string a counter, some uuid, current ms etc.
For example you can use a counter as a suffix. To keep the counter value you've to save it in the context variable, this way this property are shared between your tests inside the current execution:
import groovy.json.JsonSlurper
// create a suffix function to generate
// the suffixs for your property names based on a count
def getSuffixNameProperty = {
// check if already exists
if(context['count']){
// if exists simply add 1
context['count']++
}else{
// if not exists initialize the counter
context['count'] = 1
}
return context['count']
}
def propertyName = "token_id" + getSuffixNameProperty();
def response = context.expand( '${login#Response#declare namespace ns1=\'https://elsian/ns/20110518\'; //ns1:login_resp[1]/ns1:item[1]/ns1:response[1]}' )
def slurper = new JsonSlurper()
def result = slurper.parseText(response)
testRunner.testCase.testSuite.project.setPropertyValue(propertyName, result.data.id)

Resources