Assert operator to count before and after from various variable - assert

i have codes to get database records, send test data (not shown in below codes),
and count before/after size.
can i do below assertion to do simple math calculation directly using the printIn result?
assert responseListAfter.size() == responseListBefore.size + results
this is the full codes
//count the DB records which State = New
String dbQuery = "SELECT COUNT(*) as count FROM dispenseorders.dispenseorder where status = 'true'"
List results = CustomKeywords.'swisslog.database.getSQLResults'(GlobalVariable.dbConnString , GlobalVariable.dbUsername , GlobalVariable.dbPassword ,GlobalVariable.dbDriver ,dbQuery )
println results
//Before Refresh. count number of records in Kafka Topic A
def TopicBefore = 'A'
def NewMessageBefore = consumeMessageBefore(TopicBefore)
def responseListBefore = new JsonSlurper().parseText(consumeMessageBefore.getResponseText())
def consumeMessageBefore(def topic) {
WS.sendRequest(findTestObject('Object Repository/Kafka/subscribe_to_topic_A', [('topic_name') : topic, ('KafkaRestName') : GlobalVariable.KafkaRestName
, ('KafkaRestPort') : GlobalVariable.KafkaRestPort]))
return consumeMessageBefore = WS.sendRequestAndVerify(findTestObject('Object Repository/Kafka/consume_message_from_topic_for_DR',
[('KafkaRestName') : GlobalVariable.KafkaRestName, ('KafkaRestPort') : GlobalVariable.KafkaRestPort]))
}
println('before Request Refresh: \n' + responseListBefore.size)
WebUI.delay(10)
//after Refresh. count number of records in Kafka Topic A
def TopicAfter = 'A'
def NewMessageAfter = consumeMessageAfter(TopicAfter)
def responseListAfter = new JsonSlurper().parseText(consumeMessageAfter.getResponseText())
def consumeMessageAfter(def topic) {
WS.sendRequest(findTestObject('Object Repository/Kafka/subscribe_to_topic_for_DR', [('topic_name') : topic, ('KafkaRestName') : GlobalVariable.KafkaRestName
, ('KafkaRestPort') : GlobalVariable.KafkaRestPort]))
return consumeMessageAfter = WS.sendRequestAndVerify(findTestObject('Object Repository/Kafka/consume_message_from_topic_for_DR',
[('KafkaRestName') : GlobalVariable.KafkaRestName, ('KafkaRestPort') : GlobalVariable.KafkaRestPort]))
}
println('after Request Refresh: \n' + responseListAfter.size)
//check total messages. After Refresh count = Before Refresh count + DB records
assert responseListAfter.size() == responseListBefore.size + results

results is a list, and you need a list size (int) to add it to other ints:
assert responseListAfter.size() == responseListBefore.size() + results.size()

Related

django filter data and make union of all data points to assignt to a new data

My model is as follows
class Drawing(models.Model):
drawingJSONText = models.TextField(null=True)
project = models.CharField(max_length=250)
Sample data saved in drawingJSONText field is as below
{"points":[{"x":109,"y":286,"r":1,"color":"black"},{"x":108,"y":285,"r":1,"color":"black"},{"x":106,"y":282,"r":1,"color":"black"},{"x":103,"y":276,"r":1,"color":"black"},],"lines":[{"x1":109,"y1":286,"x2":108,"y2":285,"strokeWidth":"2","strokeColor":"black"},{"x1":108,"y1":285,"x2":106,"y2":282,"strokeWidth":"2","strokeColor":"black"},{"x1":106,"y1":282,"x2":103,"y2":276,"strokeWidth":"2","strokeColor":"black"}]}
I am trying to write a view file where the data is filtered based on project field and all the resulting queryset of drawingJSONText field are made into one data
def load(request):
""" Function to load the drawing with drawingID if it exists."""
try:
filterdata = Drawing.objects.filter(project=1)
ids = filterdata.values_list('pk', flat=True)
length = len(ids)
print(list[ids])
print(len(list(ids)))
drawingJSONData = dict()
drawingJSONData = {'points': [], 'lines': []}
for val in ids:
if length >= 0:
continue
drawingJSONData1 = json.loads(Drawing.objects.get(id=ids[val]).drawingJSONText)
drawingJSONData["points"] = drawingJSONData1["points"] + drawingJSONData["points"]
drawingJSONData["lines"] = drawingJSONData1["lines"] + drawingJSONData["lines"]
length -= 1
#print(drawingJSONData)
drawingJSONData = json.dumps(drawingJSONData)
context = {
"loadIntoJavascript": True,
"JSONData": drawingJSONData
}
# Editing response headers and returning the same
response = modifiedResponseHeaders(render(request, 'MainCanvas/index.html', context))
return response
I runs without error but it shows a blank screen
i dont think the for function is working
any suggestions on how to rectify
I think you may want
for id_val in ids:
drawingJSONData1 = json.loads(Drawing.objects.get(id=id_val).drawingJSONText)
drawingJSONData["points"] = drawingJSONData1["points"] + drawingJSONData["points"]
drawingJSONData["lines"] = drawingJSONData1["lines"] + drawingJSONData["lines"]

NetSuite - error closing return authorization using web services

Within NetSuite when trying to close out Return Authorization line items i receive the following error message:
INSUFFICIENT_PERMISSION
"You do not have permissions to set a value for element item.quantityreceived due to one of the following reasons: 1) The field is read-only; 2) An associated feature is disabled; 3) The field is available either when a record is created or updated, but not in both cases."
Here is the code:
//Pull down the RA in order to work with the line items in question
RecordRef rec = new RecordRef();
rec.internalId = internalId;
rec.type = RecordType.returnAuthorization;
rec.typeSpecified = true;
ReadResponse response = _service.get(rec);
//create the object from the response record returned
ReturnAuthorization ra = (ReturnAuthorization)response.record;
//cancel the order by updating the qty of each item to zero.
WriteResponse res = null;
ReturnAuthorizationItem[] raItemList = ra.itemList.item;
for (int lineCounter = 0; lineCounter < raItemList.Length; lineCounter++)
{
//only if the qty received is zero are we closing out the item(setting qty to zero)
if (raItemList[lineCounter].quantityReceived == 0)
{
raItemList[lineCounter].quantity = 0;
raItemList[lineCounter].quantitySpecified = true;
}
}
//create a new object and add all the changes in order to update the order lines
ReturnAuthorization updRa = new ReturnAuthorization();
updRa.internalId = internalId;
updRa.itemList = new ReturnAuthorizationItemList();
updRa.itemList.item = new ReturnAuthorizationItem[raItemList.Length];
updRa.itemList.item = raItemList;
res = _service.update(updRa);
I am trying to update the line quantity to zero, which in affect will close the Return Authorization if everything has been zeroed out. Question is how do i correct this permissions issue in order to run this update. I have tried setting other fields on this same call. No matter which field i try and update i get the same error message. This is running under an admin account and all permissions look fine as far as i can see. In fact i am running this very same logic against the SaleOrder object to close out Sales Orders with no issues.
Any help would be much appreciated.
Thanks,
Billy
You can't directly edit that line item field. That field is maintained by Netsuite and reflects Item Receipts received against the RA.
If you want to close the RA without receiving just set the line item column field "Closed" to true.
After looking at this a little closer here is the solution:
Replace the if statement in the loop with this:
//only if the qty received and returned are zero do we close out the item(setting qty to zero)
if (raItemList[lineCounter].quantityReceived == 0 && raItemList[lineCounter].quantityBilled == 0)
{
raItemList[lineCounter].quantity = 0;
raItemList[lineCounter].quantitySpecified = true;
raItemList[lineCounter].isClosed = true;
raItemList[lineCounter].isClosedSpecified = true;
raItemList[lineCounter].quantityReceivedSpecified = false;
raItemList[lineCounter].quantityBilledSpecified = false;
raItemList[lineCounter].costEstimateSpecified = false;
}
else
{
raItemList[lineCounter].quantityReceivedSpecified = false;
raItemList[lineCounter].quantityBilledSpecified = false;
raItemList[lineCounter].costEstimateSpecified = false;
}
I am guessing that the fields i had to specific as false are fields that cannot be edited, hence the need to disclude them from the update.
This is a better sample. Note the comment re orderline
/Pull down the RA in order to work with the line items in question
RecordRef rec = new RecordRef();
rec.internalId = internalId;
rec.type = RecordType.returnAuthorization;
rec.typeSpecified = true;
ReadResponse response = _service.get(rec);
//create the object from the response record returned
ReturnAuthorization ra = (ReturnAuthorization)response.record;
//cancel the order by updating the qty of each item to zero.
WriteResponse res = null;
ReturnAuthorizationItem[] raItemList = ra.itemList.item;
ReturnAuthorization updRa = new ReturnAuthorization();
updRa.internalId = internalId;
updRa.itemList = new ReturnAuthorizationItemList();
ReturnAuthorizationItem[] updateItems = new ReturnAuthorizationItem[raItemList.Length];
for (int lineCounter = 0; lineCounter < raItemList.Length; lineCounter++)
{
updateItems[lineCounter].line = raItemList[lineCounter].line; // you'll need to test this. Setting only the line should result in no changes to the RA line items that are not to be closed. use the &xml=T view before and after to make sure orderline (hidden) is still populated properly.
//only if the qty received is zero are we closing out the item(setting qty to zero)
if (raItemList[lineCounter].quantityReceived == 0)
{
updateItems[lineCounter].isClosed = true;
// raItemList[lineCounter].quantitySpecified = true; // is quantitySpecified a field? it wasn't as of the 2012.2 endpoint
}
}
//create a new object and add all the changes in order to update the order lines
updRa.itemList.item = updateItems;
res = _service.update(updRa);

Get SOAP attachment

There is a lot of questions with same subject, but no replies, especially about receiving. There exist example how to send attachment, but I didn't found how to receive it.
Is there any solution on python for receiving attachments? I even agree to change my SOAP tool from suds to anything that will works.
Thank you in advance.
I solved it with suds.
def GetWithFile(self, client, servicename, modelthings):
func = client.get_suds_func('Retrieve' + servicename)
clientclass = func.clientclass({})
SoapClient = clientclass(func.client, func.method)
binding = func.method.binding.input
soap_xml = binding.get_message(func.method, [modelthings], {})
soap_xml.children[0].children[1].children[0].attributes.append(u'attachmentInfo="true"')
soap_xml.children[0].children[1].children[0].attributes.append(u'attachmentData="true"')
soap_xml.children[0].children[1].children[0].attributes.append(u'ignoreEmptyElements="true"')
SoapClient.last_sent(soap_xml)
plugins = PluginContainer(SoapClient.options.plugins)
plugins.message.marshalled(envelope=soap_xml.root())
if SoapClient.options.prettyxml:
soap_xml = soap_xml.str()
else:
soap_xml = soap_xml.plain()
soap_xml = soap_xml.encode('utf-8')
plugins.message.sending(envelope=soap_xml)
request = Request(SoapClient.location(), soap_xml)
request.headers = SoapClient.headers()
reply = SoapClient.options.transport.send(request)
print(reply)
Files = []
boundary = self.find_substring(reply.headers['content-type'], 'boundary="', '"')
if boundary is not "":
list_of_data = reply.message.split(boundary)
list_of_data.pop(0)
list_of_data.pop(len(list_of_data) - 1)
soap_body = '<SOAP-ENV:Envelope' + self.find_substring(list_of_data[0], '<SOAP-ENV:Envelope', '</SOAP-ENV:Envelope>') + '</SOAP-ENV:Envelope>'
for line in list_of_data[1:]:
File = SMFile()
Files.append(File)
File.filename = self.find_substring(line, 'Content-Location: ', '\r\n')
File.key = self.find_substring(line, 'Content-ID: ', '\r\n')
idx = line.index( 'Content-ID:' )
start_idx = line.index( '\r\n\r\n' , idx ) + len('\r\n\r\n')
fin_idx = line.rindex( '\r\n--', start_idx )
File.body = line[start_idx: fin_idx]
File.size = fin_idx - start_idx
else:
soap_body = '<SOAP-ENV:Envelope' + self.find_substring(reply.message, '<SOAP-ENV:Envelope', '</SOAP-ENV:Envelope>') + '</SOAP-ENV:Envelope>'
ctx = plugins.message.received(reply=soap_body)
soap_body = ctx.reply
if SoapClient.options.retxml:
answer = soap_body
else:
answer = SoapClient.succeeded(binding, soap_body)
dict = {}
self.FieldsToDict(answer.model.instance, dict)
return {u'body': answer, u'Files': Files}
Here we extract some low level of suds, being able to fix any field in envelope. Then, after reply was got, we parse all boundaries and receive as many files, as we got.

Add map elements to list with a loop

I am trying to populate a list with maps created from objects in a query/findAllBy... I always end up with list of maps identical to the last map in the loop.
I have set break points and stepped through the method and found that 1) the data returned from the query is correct, 2) as I step through the loop the data is inserted into the map(s) correctly, 3) the failure comes when inserting the map into the list. All the methods I've used to insert elements into a list (.add, .push, <<, list[(i)] = map, etc) end up overwriting all the previous elements in the list.
Please help. I don't know why this is happening. Hopefully this is an easy one for someone out there.
def shiftRecords = Shift.findAllByUserAndStartTimeBetween( userInstance, startDate, endDate )
ArrayList allShifts = new ArrayList()
LinkedHashMap thisShift = new LinkedHashMap()
def size = shiftRecords.size()
for ( int i = 0; i < size; i++ ){
thisShift["id"] = shiftRecords[(i)].id
thisShift["user"] = shiftRecords[(i)].user
thisShift["startTime"] = shiftRecords[(i)].startTime
thisShift["posCode"] = shiftRecords[(i)].posCode
thisShift["deptCode"] = shiftRecords[(i)].deptCode
thisShift["billingIDX"] = shiftRecords[(i)].billingIDX
Position thisPos = Position.findByPositionCode( thisShift.posCode )
thisShift["posTitle"] = thisPos.shortTitle
thisShift["deptTitle"] = thisPos.departmentTitle
allShifts.add( (i), thisShift )
}
I need the results of allShifts to be a list of maps with the selected data pulled from the Shift query results. I've tried using shiftRecords.each and eachWithIndex. The problem happens with any type of loop at the point where thisShift map is inserted into allShifts. It doesnt just insert one instance of the map, but replaces all list elements with the current thisShift map.
def shiftRecords = Shift.findAllByUserAndStartTimeBetween(
userInstance, startDate, endDate )
ArrayList allShifts = new ArrayList()
def size = shiftRecords.size()
for ( int i = 0; i < size; i++ ){
LinkedHashMap thisShift = new LinkedHashMap()
thisShift["id"] = shiftRecords[(i)].id
thisShift["user"] = shiftRecords[(i)].user
thisShift["startTime"] = shiftRecords[(i)].startTime
thisShift["posCode"] = shiftRecords[(i)].posCode
thisShift["deptCode"] = shiftRecords[(i)].deptCode
thisShift["billingIDX"] = shiftRecords[(i)].billingIDX
Position thisPos = Position.findByPositionCode( thisShift.posCode )
thisShift["posTitle"] = thisPos.shortTitle
thisShift["deptTitle"] = thisPos.departmentTitle
allShifts << thisShift
}
You need to create a new map each time you iterate over shiftRecords. Although, the above code can be overly simplified in groovy as below:
def shiftRecords = Shift.findAllByUserAndStartTimeBetween(
userInstance, startDate, endDate )
def allShifts = []
shiftRecords.each{
def thisShift = [:]
thisShift.id = it.id
thisShift.user = it.user
thisShift.startTime = it.startTime
thisShift.posCode = it.posCode
thisShift.deptCode = it.deptCode
thisShift.billingIDX = it.billingIDX
Position thisPos = Position.findByPositionCode( thisShift.posCode )
thisShift.posTitle = thisPos.shortTitle
thisShift.deptTitle = thisPos.departmentTitle
allShifts << thisShift
}
Try:
def shiftRecords = Shift.findAllByUserAndStartTimeBetween( userInstance, startDate, endDate )
def allShifts = shiftRecords.collect { it ->
def pos = Position.findByPositionCode( it.posCode )
[ id : it.id,
user : it.user,
startTime : it.startTime,
posCode : it.posCode,
deptCode : it.deptCode,
billingIDX : it.billingIDX,
posTitle : pos.shortTitle,
deptTitle : pos.departmentTitle ]
}

JSON.parse error on simplejson return in Django

I have a view page that currently has two columns of data shown, soon to be expanded to four. Each column contains the result of a QuerySet for that particular model.
Here's what I have in my views.py method:
if request.REQUEST["type"] == "text":
client = Client.objects.get(client_name = request.REQUEST["search"])
peerList = ClientPeers.objects.prefetch_related().filter(client = client.client)
compList = ClientCompetitors.objects.prefetch_related().filter(client = client.client)
else:
peerList = ClientPeers.objects.prefetch_related().filter(client = request.REQUEST["search"])
compList = ClientCompetitors.objects.prefetch_related().filter(client = request.REQUEST["search"])
for peer in peerList:
peerlst.append({"pid" : peer.parentorg.parentorg, "pname" : peer.parentorg.parentorgname})
for comp in compList:
complst.append({"cid" : comp.parentorg.parentorg, "cname" : comp.parentorg.parentorgname})
lst.append(simplejson.dumps(peerlst))
lst.append(simplejson.dumps(complst))
return HttpResponse(simplejson.dumps(lst), mimetype = "text/json")
This allows me to send a 2D array of data to the browser in the format
[ { //JSON }, { //JSON } ]
In my jQuery.ajax success function, I have
function handler(results) {
var data = JSON.parse(results);
for (var i = 0; i < data[0].length; i++)
$("#available_peers").append("<li>" + data[0][i].pname + "</li>");
for (var i = 0; i < data[1].length; i++)
$("#available_competitors").append("<li>" + data[1][i].cname + "</li>");
Firebug shows that the GET request works and I can see the data in the response tab. However, the console prints out
SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data
var data = JSON.parse(results)
This error disappears if I replace var data = JSON.parse(results) with
var peers = JSON.parse(data[0]);
var comps = JSON.parse(data[1]);
Why does one method work but another doesn't?
The jQuery ajax() call will make an intelligent guess as to the returned data type. In your example, function handler(results), the results variable will already be a decoded JSON object, containing two items in an array. The reason that JSON.parse(data[0]) works, is that you have returned JSON encoded data as a string.
Don't encode the individual list elements to JSON before placing in the output array:
lst.append(peerlst) # <-- Don't encode to JSON string here
lst.append(complst)
return HttpResponse(simplejson.dumps(lst), mimetype = "application/json") # <-- Single JSON encoding